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

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. class ProductVariantsSubscriber implements EventSubscriberInterface
  20. {
  21.     private SyncServiceInterface $syncService;
  22.     private Connection $connection;
  23.     private EntityRepositoryInterface $groupRepository;
  24.     private EntityRepositoryInterface $optionRepository;
  25.     private array $groupIdCache = [];
  26.     private array $optionIdCache = [];
  27.     public function __construct(
  28.         SyncServiceInterface $syncService,
  29.         Connection $connection,
  30.         EntityRepositoryInterface $groupRepository,
  31.         EntityRepositoryInterface $optionRepository
  32.     ) {
  33.         $this->syncService $syncService;
  34.         $this->connection $connection;
  35.         $this->groupRepository $groupRepository;
  36.         $this->optionRepository $optionRepository;
  37.     }
  38.     /**
  39.      * @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
  40.      */
  41.     public static function getSubscribedEvents()
  42.     {
  43.         return [
  44.             ImportExportAfterImportRecordEvent::class => 'onAfterImportRecord',
  45.         ];
  46.     }
  47.     public function onAfterImportRecord(ImportExportAfterImportRecordEvent $event): void
  48.     {
  49.         $row $event->getRow();
  50.         $entityName $event->getConfig()->get('sourceEntity');
  51.         $entityWrittenEvents $event->getResult()->getEvents();
  52.         if ($entityName !== ProductDefinition::ENTITY_NAME || empty($row['variants']) || !$entityWrittenEvents) {
  53.             return;
  54.         }
  55.         $variants $this->parseVariantString($row['variants']);
  56.         $entityWrittenEvent $entityWrittenEvents->filter(function ($event) {
  57.             return $event instanceof EntityWrittenEvent && $event->getEntityName() === ProductDefinition::ENTITY_NAME;
  58.         })->first();
  59.         if (!$entityWrittenEvent instanceof EntityWrittenEvent) {
  60.             return;
  61.         }
  62.         $writeResults $entityWrittenEvent->getWriteResults();
  63.         if (empty($writeResults)) {
  64.             return;
  65.         }
  66.         $parentId $writeResults[0]->getPrimaryKey();
  67.         $parentPayload $writeResults[0]->getPayload();
  68.         if (!\is_string($parentId)) {
  69.             return;
  70.         }
  71.         $payload $this->getCombinationsPayload($variants$parentId$parentPayload['productNumber']);
  72.         $variantIds array_column($payload'id');
  73.         $this->connection->executeStatement(
  74.             'DELETE FROM `product_option` WHERE `product_id` IN (:ids);',
  75.             ['ids' => Uuid::fromHexToBytesList($variantIds)],
  76.             ['ids' => Connection::PARAM_STR_ARRAY]
  77.         );
  78.         $configuratorSettingPayload $this->getProductConfiguratorSettingPayload($payload$parentId);
  79.         $this->connection->executeStatement(
  80.             'DELETE FROM `product_configurator_setting` WHERE `product_id` = :parentId AND `id` NOT IN (:ids);',
  81.             [
  82.                 'parentId' => Uuid::fromHexToBytes($parentId),
  83.                 'ids' => Uuid::fromHexToBytesList(array_column($configuratorSettingPayload'id')),
  84.             ],
  85.             ['ids' => Connection::PARAM_STR_ARRAY]
  86.         );
  87.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  88.             $behavior = new SyncBehavior();
  89.         } else {
  90.             $behavior = new SyncBehavior(truetrue);
  91.         }
  92.         $result $this->syncService->sync([
  93.             new SyncOperation(
  94.                 'write',
  95.                 ProductDefinition::ENTITY_NAME,
  96.                 SyncOperation::ACTION_UPSERT,
  97.                 $payload
  98.             ),
  99.             new SyncOperation(
  100.                 'write',
  101.                 ProductConfiguratorSettingDefinition::ENTITY_NAME,
  102.                 SyncOperation::ACTION_UPSERT,
  103.                 $configuratorSettingPayload
  104.             ),
  105.         ], Context::createDefaultContext(), $behavior);
  106.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  107.             // @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
  108.             return;
  109.         }
  110.         if (!$result->isSuccess()) {
  111.             $operation $result->get('write');
  112.             throw new ProcessingException(sprintf(
  113.                 'Failed writing variants for %s with errors: %s',
  114.                 $parentPayload['productNumber'],
  115.                 $operation json_encode(array_column($operation->getResult(), 'errors')) : ''
  116.             ));
  117.         }
  118.     }
  119.     /**
  120.      * convert "size: m, l, xl" to ["size|m", "size|l", "size|xl"]
  121.      */
  122.     private function parseVariantString(string $variantsString): array
  123.     {
  124.         $result = [];
  125.         $groups explode('|'$variantsString);
  126.         foreach ($groups as $group) {
  127.             $groupOptions explode(':'$group);
  128.             if (\count($groupOptions) !== 2) {
  129.                 $this->throwExceptionFailedParsingVariants($variantsString);
  130.             }
  131.             $groupName trim($groupOptions[0]);
  132.             $options array_filter(array_map('trim'explode(','$groupOptions[1])));
  133.             if (empty($groupName) || empty($options)) {
  134.                 $this->throwExceptionFailedParsingVariants($variantsString);
  135.             }
  136.             $options array_map(function ($option) use ($groupName) {
  137.                 return sprintf('%s|%s'$groupName$option);
  138.             }, $options);
  139.             $result[] = $options;
  140.         }
  141.         return $result;
  142.     }
  143.     private function throwExceptionFailedParsingVariants(string $variantsString): void
  144.     {
  145.         throw new ProcessingException(sprintf(
  146.             'Failed parsing variants from string "%s", valid format is: "size: L, XL, | color: Green, White"',
  147.             $variantsString
  148.         ));
  149.     }
  150.     private function getCombinationsPayload(array $variantsstring $parentIdstring $productNumber): array
  151.     {
  152.         $combinations $this->getCombinations($variants);
  153.         $payload = [];
  154.         foreach ($combinations as $key => $combination) {
  155.             $options = [];
  156.             foreach ($combination as $option) {
  157.                 list($group$option) = explode('|'$option);
  158.                 $optionId $this->getOptionId($group$option);
  159.                 $groupId $this->getGroupId($group);
  160.                 $options[] = [
  161.                     'id' => $optionId,
  162.                     'name' => $option,
  163.                     'group' => [
  164.                         'id' => $groupId,
  165.                         'name' => $group,
  166.                     ],
  167.                 ];
  168.             }
  169.             $variantId Uuid::fromStringToHex(sprintf('%s.%s'$parentId$key));
  170.             $variantProductNumber sprintf('%s.%s'$productNumber$key);
  171.             $payload[] = [
  172.                 'id' => $variantId,
  173.                 'parentId' => $parentId,
  174.                 'productNumber' => $variantProductNumber,
  175.                 'stock' => 0,
  176.                 'options' => $options,
  177.             ];
  178.         }
  179.         return $payload;
  180.     }
  181.     /**
  182.      * convert [["size|m", "size|l"], ["color|blue", "color|red"]]
  183.      * to [["size|m", "color|blue"], ["size|l", "color|blue"], ["size|m", "color|red"], ["size|l", "color|red"]]
  184.      */
  185.     private function getCombinations(array $variantsint $currentIndex 0): array
  186.     {
  187.         if (!isset($variants[$currentIndex])) {
  188.             return [];
  189.         }
  190.         if ($currentIndex === \count($variants) - 1) {
  191.             return $variants[$currentIndex];
  192.         }
  193.         // get combinations from subsequent arrays
  194.         $combinations $this->getCombinations($variants$currentIndex 1);
  195.         $result = [];
  196.         // concat each array from tmp with each element from $variants[$i]
  197.         foreach ($variants[$currentIndex] as $variant) {
  198.             foreach ($combinations as $combination) {
  199.                 $result[] = \is_array($combination) ? array_merge([$variant], $combination) : [$variant$combination];
  200.             }
  201.         }
  202.         return $result;
  203.     }
  204.     private function getProductConfiguratorSettingPayload(array $variantsPayloadstring $parentId): array
  205.     {
  206.         $options array_merge(...array_column($variantsPayload'options'));
  207.         $optionIds array_unique(array_column($options'id'));
  208.         $payload = [];
  209.         foreach ($optionIds as $optionId) {
  210.             $payload[] = [
  211.                 'id' => Uuid::fromStringToHex(sprintf('%s_configurator'$optionId)),
  212.                 'optionId' => $optionId,
  213.                 'productId' => $parentId,
  214.             ];
  215.         }
  216.         return $payload;
  217.     }
  218.     private function getGroupId(string $groupName): string
  219.     {
  220.         $groupId Uuid::fromStringToHex($groupName);
  221.         if (isset($this->groupIdCache[$groupId])) {
  222.             return $this->groupIdCache[$groupId];
  223.         }
  224.         $criteria = new Criteria();
  225.         $criteria->addFilter(new EqualsFilter('name'$groupName));
  226.         $group $this->groupRepository->search($criteriaContext::createDefaultContext())->first();
  227.         if ($group !== null) {
  228.             $this->groupIdCache[$groupId] = $group->getId();
  229.             return $group->getId();
  230.         }
  231.         $this->groupIdCache[$groupId] = $groupId;
  232.         return $groupId;
  233.     }
  234.     private function getOptionId(string $groupNamestring $optionName): string
  235.     {
  236.         $optionId Uuid::fromStringToHex(sprintf('%s.%s'$groupName$optionName));
  237.         if (isset($this->optionIdCache[$optionId])) {
  238.             return $this->optionIdCache[$optionId];
  239.         }
  240.         $criteria = new Criteria();
  241.         $criteria->addFilter(new EqualsFilter('name'$optionName));
  242.         $criteria->addFilter(new EqualsFilter('group.name'$groupName));
  243.         $option $this->optionRepository->search($criteriaContext::createDefaultContext())->first();
  244.         if ($option !== null) {
  245.             $this->optionIdCache[$optionId] = $option->getId();
  246.             return $option->getId();
  247.         }
  248.         $this->optionIdCache[$optionId] = $optionId;
  249.         return $optionId;
  250.     }
  251. }