src/Core/Content/ImportExport/Event/Subscriber/ProductVariantsSubscriber.php line 62

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