vendor/shopware/core/Content/ImportExport/Event/Subscriber/ProductVariantsSubscriber.php line 71

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\ImportExport\Event\Subscriber;
  3. use Doctrine\DBAL\Connection;
  4. use Shopware\Core\Content\ImportExport\Event\ImportExportAfterImportRecordEvent;
  5. use Shopware\Core\Content\ImportExport\Exception\ProcessingException;
  6. use Shopware\Core\Content\Product\Aggregate\ProductConfiguratorSetting\ProductConfiguratorSettingDefinition;
  7. use Shopware\Core\Content\Product\ProductDefinition;
  8. use Shopware\Core\Framework\Api\Sync\SyncBehavior;
  9. use Shopware\Core\Framework\Api\Sync\SyncOperation;
  10. use Shopware\Core\Framework\Api\Sync\SyncServiceInterface;
  11. use Shopware\Core\Framework\Context;
  12. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  16. use Shopware\Core\Framework\Feature;
  17. use Shopware\Core\Framework\Uuid\Uuid;
  18. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  19. use Symfony\Contracts\Service\ResetInterface;
  20. /**
  21.  * @deprecated tag:v6.5.0 - reason:becomes-internal - EventSubscribers will become internal in v6.5.0
  22.  */
  23. class ProductVariantsSubscriber implements EventSubscriberInterfaceResetInterface
  24. {
  25.     private SyncServiceInterface $syncService;
  26.     private Connection $connection;
  27.     private EntityRepositoryInterface $groupRepository;
  28.     private EntityRepositoryInterface $optionRepository;
  29.     /**
  30.      * @var array<string, string>
  31.      */
  32.     private array $groupIdCache = [];
  33.     /**
  34.      * @var array<string, string>
  35.      */
  36.     private array $optionIdCache = [];
  37.     /**
  38.      * @internal
  39.      */
  40.     public function __construct(
  41.         SyncServiceInterface $syncService,
  42.         Connection $connection,
  43.         EntityRepositoryInterface $groupRepository,
  44.         EntityRepositoryInterface $optionRepository
  45.     ) {
  46.         $this->syncService $syncService;
  47.         $this->connection $connection;
  48.         $this->groupRepository $groupRepository;
  49.         $this->optionRepository $optionRepository;
  50.     }
  51.     /**
  52.      * @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
  53.      */
  54.     public static function getSubscribedEvents()
  55.     {
  56.         return [
  57.             ImportExportAfterImportRecordEvent::class => 'onAfterImportRecord',
  58.         ];
  59.     }
  60.     public function onAfterImportRecord(ImportExportAfterImportRecordEvent $event): void
  61.     {
  62.         $row $event->getRow();
  63.         $entityName $event->getConfig()->get('sourceEntity');
  64.         $entityWrittenEvents $event->getResult()->getEvents();
  65.         if ($entityName !== ProductDefinition::ENTITY_NAME || empty($row['variants']) || !$entityWrittenEvents) {
  66.             return;
  67.         }
  68.         $variants $this->parseVariantString($row['variants']);
  69.         $entityWrittenEvent $entityWrittenEvents->filter(function ($event) {
  70.             return $event instanceof EntityWrittenEvent && $event->getEntityName() === ProductDefinition::ENTITY_NAME;
  71.         })->first();
  72.         if (!$entityWrittenEvent instanceof EntityWrittenEvent) {
  73.             return;
  74.         }
  75.         $writeResults $entityWrittenEvent->getWriteResults();
  76.         if (empty($writeResults)) {
  77.             return;
  78.         }
  79.         $parentId $writeResults[0]->getPrimaryKey();
  80.         $parentPayload $writeResults[0]->getPayload();
  81.         if (!\is_string($parentId)) {
  82.             return;
  83.         }
  84.         $payload $this->getCombinationsPayload($variants$parentId$parentPayload['productNumber']);
  85.         $variantIds array_column($payload'id');
  86.         $this->connection->executeStatement(
  87.             'DELETE FROM `product_option` WHERE `product_id` IN (:ids);',
  88.             ['ids' => Uuid::fromHexToBytesList($variantIds)],
  89.             ['ids' => Connection::PARAM_STR_ARRAY]
  90.         );
  91.         $configuratorSettingPayload $this->getProductConfiguratorSettingPayload($payload$parentId);
  92.         $this->connection->executeStatement(
  93.             'DELETE FROM `product_configurator_setting` WHERE `product_id` = :parentId AND `id` NOT IN (:ids);',
  94.             [
  95.                 'parentId' => Uuid::fromHexToBytes($parentId),
  96.                 'ids' => Uuid::fromHexToBytesList(array_column($configuratorSettingPayload'id')),
  97.             ],
  98.             ['ids' => Connection::PARAM_STR_ARRAY]
  99.         );
  100.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  101.             $behavior = new SyncBehavior();
  102.         } else {
  103.             $behavior = new SyncBehavior(truetrue);
  104.         }
  105.         $result $this->syncService->sync([
  106.             new SyncOperation(
  107.                 'write',
  108.                 ProductDefinition::ENTITY_NAME,
  109.                 SyncOperation::ACTION_UPSERT,
  110.                 $payload
  111.             ),
  112.             new SyncOperation(
  113.                 'write',
  114.                 ProductConfiguratorSettingDefinition::ENTITY_NAME,
  115.                 SyncOperation::ACTION_UPSERT,
  116.                 $configuratorSettingPayload
  117.             ),
  118.         ], Context::createDefaultContext(), $behavior);
  119.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  120.             // @internal (flag:FEATURE_NEXT_15815) - remove code below, "isSuccess" function will be removed, simply return because sync service would throw an exception in error case
  121.             return;
  122.         }
  123.         if (!$result->isSuccess()) {
  124.             $operation $result->get('write');
  125.             throw new ProcessingException(sprintf(
  126.                 'Failed writing variants for %s with errors: %s',
  127.                 $parentPayload['productNumber'],
  128.                 $operation json_encode(array_column($operation->getResult(), 'errors')) : ''
  129.             ));
  130.         }
  131.     }
  132.     public function reset(): void
  133.     {
  134.         $this->groupIdCache = [];
  135.         $this->optionIdCache = [];
  136.     }
  137.     /**
  138.      * convert "size: m, l, xl" to ["size|m", "size|l", "size|xl"]
  139.      *
  140.      * @return list<list<string>>
  141.      */
  142.     private function parseVariantString(string $variantsString): array
  143.     {
  144.         $result = [];
  145.         $groups explode('|'$variantsString);
  146.         foreach ($groups as $group) {
  147.             $groupOptions explode(':'$group);
  148.             if (\count($groupOptions) !== 2) {
  149.                 $this->throwExceptionFailedParsingVariants($variantsString);
  150.             }
  151.             $groupName trim($groupOptions[0]);
  152.             $options array_filter(array_map('trim'explode(','$groupOptions[1])));
  153.             if (empty($groupName) || empty($options)) {
  154.                 $this->throwExceptionFailedParsingVariants($variantsString);
  155.             }
  156.             $options array_map(function ($option) use ($groupName) {
  157.                 return sprintf('%s|%s'$groupName$option);
  158.             }, $options);
  159.             $result[] = $options;
  160.         }
  161.         return $result;
  162.     }
  163.     private function throwExceptionFailedParsingVariants(string $variantsString): void
  164.     {
  165.         throw new ProcessingException(sprintf(
  166.             'Failed parsing variants from string "%s", valid format is: "size: L, XL, | color: Green, White"',
  167.             $variantsString
  168.         ));
  169.     }
  170.     /**
  171.      * @param list<list<string>> $variants
  172.      *
  173.      * @return list<array<string, mixed>>
  174.      */
  175.     private function getCombinationsPayload(array $variantsstring $parentIdstring $productNumber): array
  176.     {
  177.         $combinations $this->getCombinations($variants);
  178.         $payload = [];
  179.         foreach ($combinations as $key => $combination) {
  180.             $options = [];
  181.             if (\is_string($combination)) {
  182.                 $combination = [$combination];
  183.             }
  184.             foreach ($combination as $option) {
  185.                 list($group$option) = explode('|'$option);
  186.                 $optionId $this->getOptionId($group$option);
  187.                 $groupId $this->getGroupId($group);
  188.                 $options[] = [
  189.                     'id' => $optionId,
  190.                     'name' => $option,
  191.                     'group' => [
  192.                         'id' => $groupId,
  193.                         'name' => $group,
  194.                     ],
  195.                 ];
  196.             }
  197.             $variantId Uuid::fromStringToHex(sprintf('%s.%s'$parentId$key));
  198.             $variantProductNumber sprintf('%s.%s'$productNumber$key);
  199.             $payload[] = [
  200.                 'id' => $variantId,
  201.                 'parentId' => $parentId,
  202.                 'productNumber' => $variantProductNumber,
  203.                 'stock' => 0,
  204.                 'options' => $options,
  205.             ];
  206.         }
  207.         return $payload;
  208.     }
  209.     /**
  210.      * convert [["size|m", "size|l"], ["color|blue", "color|red"]]
  211.      * to [["size|m", "color|blue"], ["size|l", "color|blue"], ["size|m", "color|red"], ["size|l", "color|red"]]
  212.      *
  213.      * @param list<list<string>> $variants
  214.      *
  215.      * @return list<list<string>>|list<string>
  216.      */
  217.     private function getCombinations(array $variantsint $currentIndex 0): array
  218.     {
  219.         if (!isset($variants[$currentIndex])) {
  220.             return [];
  221.         }
  222.         if ($currentIndex === \count($variants) - 1) {
  223.             return $variants[$currentIndex];
  224.         }
  225.         // get combinations from subsequent arrays
  226.         $combinations $this->getCombinations($variants$currentIndex 1);
  227.         $result = [];
  228.         // concat each array from tmp with each element from $variants[$i]
  229.         foreach ($variants[$currentIndex] as $variant) {
  230.             foreach ($combinations as $combination) {
  231.                 $result[] = \is_array($combination) ? array_merge([$variant], $combination) : [$variant$combination];
  232.             }
  233.         }
  234.         return $result;
  235.     }
  236.     /**
  237.      * @param list<array<string, mixed>> $variantsPayload
  238.      *
  239.      * @return list<array<string, mixed>>
  240.      */
  241.     private function getProductConfiguratorSettingPayload(array $variantsPayloadstring $parentId): array
  242.     {
  243.         $options array_merge(...array_column($variantsPayload'options'));
  244.         $optionIds array_unique(array_column($options'id'));
  245.         $payload = [];
  246.         foreach ($optionIds as $optionId) {
  247.             $payload[] = [
  248.                 'id' => Uuid::fromStringToHex(sprintf('%s_configurator'$optionId)),
  249.                 'optionId' => $optionId,
  250.                 'productId' => $parentId,
  251.             ];
  252.         }
  253.         return $payload;
  254.     }
  255.     private function getGroupId(string $groupName): string
  256.     {
  257.         $groupId Uuid::fromStringToHex($groupName);
  258.         if (isset($this->groupIdCache[$groupId])) {
  259.             return $this->groupIdCache[$groupId];
  260.         }
  261.         $criteria = new Criteria();
  262.         $criteria->addFilter(new EqualsFilter('name'$groupName));
  263.         $group $this->groupRepository->search($criteriaContext::createDefaultContext())->first();
  264.         if ($group !== null) {
  265.             $this->groupIdCache[$groupId] = $group->getId();
  266.             return $group->getId();
  267.         }
  268.         $this->groupIdCache[$groupId] = $groupId;
  269.         return $groupId;
  270.     }
  271.     private function getOptionId(string $groupNamestring $optionName): string
  272.     {
  273.         $optionId Uuid::fromStringToHex(sprintf('%s.%s'$groupName$optionName));
  274.         if (isset($this->optionIdCache[$optionId])) {
  275.             return $this->optionIdCache[$optionId];
  276.         }
  277.         $criteria = new Criteria();
  278.         $criteria->addFilter(new EqualsFilter('name'$optionName));
  279.         $criteria->addFilter(new EqualsFilter('group.name'$groupName));
  280.         $option $this->optionRepository->search($criteriaContext::createDefaultContext())->first();
  281.         if ($option !== null) {
  282.             $this->optionIdCache[$optionId] = $option->getId();
  283.             return $option->getId();
  284.         }
  285.         $this->optionIdCache[$optionId] = $optionId;
  286.         return $optionId;
  287.     }
  288. }