vendor/shopware/core/Content/ImportExport/Event/Subscriber/ProductCategoryPathsSubscriber.php line 54

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\ImportExport\Event\Subscriber;
  3. use Shopware\Core\Content\Category\CategoryDefinition;
  4. use Shopware\Core\Content\ImportExport\Event\ImportExportBeforeImportRecordEvent;
  5. use Shopware\Core\Content\ImportExport\Exception\ProcessingException;
  6. use Shopware\Core\Content\Product\ProductDefinition;
  7. use Shopware\Core\Framework\Api\Sync\SyncBehavior;
  8. use Shopware\Core\Framework\Api\Sync\SyncOperation;
  9. use Shopware\Core\Framework\Api\Sync\SyncServiceInterface;
  10. use Shopware\Core\Framework\Context;
  11. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  14. use Shopware\Core\Framework\Feature;
  15. use Shopware\Core\Framework\Uuid\Uuid;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Contracts\Service\ResetInterface;
  18. /**
  19.  * @deprecated tag:v6.5.0 - reason:becomes-internal - EventSubscribers will become internal in v6.5.0
  20.  */
  21. class ProductCategoryPathsSubscriber implements EventSubscriberInterfaceResetInterface
  22. {
  23.     private EntityRepositoryInterface $categoryRepository;
  24.     private SyncServiceInterface $syncService;
  25.     /**
  26.      * @var array<string, string>
  27.      */
  28.     private array $categoryIdCache = [];
  29.     /**
  30.      * @internal
  31.      */
  32.     public function __construct(EntityRepositoryInterface $categoryRepositorySyncServiceInterface $syncService)
  33.     {
  34.         $this->categoryRepository $categoryRepository;
  35.         $this->syncService $syncService;
  36.     }
  37.     /**
  38.      * @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
  39.      */
  40.     public static function getSubscribedEvents()
  41.     {
  42.         return [
  43.             ImportExportBeforeImportRecordEvent::class => 'categoryPathsToAssignment',
  44.         ];
  45.     }
  46.     public function categoryPathsToAssignment(ImportExportBeforeImportRecordEvent $event): void
  47.     {
  48.         $row $event->getRow();
  49.         $entityName $event->getConfig()->get('sourceEntity');
  50.         if ($entityName !== ProductDefinition::ENTITY_NAME || empty($row['category_paths'])) {
  51.             return;
  52.         }
  53.         $result = [];
  54.         $categoriesPaths explode('|'$row['category_paths']);
  55.         $newCategoriesPayload = [];
  56.         foreach ($categoriesPaths as $path) {
  57.             $categories explode('>'$path);
  58.             $categoryId null;
  59.             foreach ($categories as $currentIndex => $categoryName) {
  60.                 if (empty($categoryName)) {
  61.                     continue;
  62.                 }
  63.                 $partialPath implode('>', \array_slice($categories0$currentIndex 1));
  64.                 if (isset($this->categoryIdCache[$partialPath])) {
  65.                     $categoryId $this->categoryIdCache[$partialPath];
  66.                     continue;
  67.                 }
  68.                 $criteria = new Criteria();
  69.                 $criteria->addFilter(new EqualsFilter('name'$categoryName));
  70.                 $criteria->addFilter(new EqualsFilter('parentId'$categoryId));
  71.                 $category $this->categoryRepository->search($criteriaContext::createDefaultContext())->first();
  72.                 if ($category === null && $categoryId === null) {
  73.                     break;
  74.                 }
  75.                 if ($category !== null) {
  76.                     $categoryId $category->getId();
  77.                     $this->categoryIdCache[$partialPath] = $categoryId;
  78.                     continue;
  79.                 }
  80.                 $parentId $categoryId;
  81.                 $categoryId Uuid::fromStringToHex($partialPath);
  82.                 $this->categoryIdCache[$partialPath] = $categoryId;
  83.                 $newCategoriesPayload[] = [
  84.                     'id' => $categoryId,
  85.                     'parent' => ['id' => $parentId],
  86.                     'name' => $categoryName,
  87.                 ];
  88.             }
  89.             if ($categoryId !== null) {
  90.                 $result[] = ['id' => $categoryId];
  91.             }
  92.         }
  93.         if (!empty($newCategoriesPayload)) {
  94.             $this->createNewCategories($newCategoriesPayload$row['category_paths']);
  95.         }
  96.         $record $event->getRecord();
  97.         $record['categories'] = !empty($record['categories']) ? array_merge($record['categories'], $result) : $result;
  98.         $event->setRecord($record);
  99.     }
  100.     public function reset(): void
  101.     {
  102.         $this->categoryIdCache = [];
  103.     }
  104.     /**
  105.      * @param list<array<string, mixed>> $payload
  106.      */
  107.     private function createNewCategories(array $payloadstring $categoryPaths): void
  108.     {
  109.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  110.             $behavior = new SyncBehavior();
  111.         } else {
  112.             $behavior = new SyncBehavior(truetrue);
  113.         }
  114.         $result $this->syncService->sync([
  115.             new SyncOperation(
  116.                 'write',
  117.                 CategoryDefinition::ENTITY_NAME,
  118.                 SyncOperation::ACTION_UPSERT,
  119.                 $payload
  120.             ),
  121.         ], Context::createDefaultContext(), $behavior);
  122.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  123.             // @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
  124.             return;
  125.         }
  126.         if (!$result->isSuccess()) {
  127.             $operation $result->get('write');
  128.             throw new ProcessingException(sprintf(
  129.                 'Failed writing categories for path %s with errors: %s',
  130.                 $categoryPaths,
  131.                 $operation json_encode(array_column($operation->getResult(), 'errors')) : ''
  132.             ));
  133.         }
  134.     }
  135. }