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

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. class ProductCategoryPathsSubscriber implements EventSubscriberInterface
  18. {
  19.     private EntityRepositoryInterface $categoryRepository;
  20.     private SyncServiceInterface $syncService;
  21.     private array $categoryIdCache = [];
  22.     public function __construct(EntityRepositoryInterface $categoryRepositorySyncServiceInterface $syncService)
  23.     {
  24.         $this->categoryRepository $categoryRepository;
  25.         $this->syncService $syncService;
  26.     }
  27.     /**
  28.      * @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
  29.      */
  30.     public static function getSubscribedEvents()
  31.     {
  32.         return [
  33.             ImportExportBeforeImportRecordEvent::class => 'categoryPathsToAssignment',
  34.         ];
  35.     }
  36.     public function categoryPathsToAssignment(ImportExportBeforeImportRecordEvent $event): void
  37.     {
  38.         $row $event->getRow();
  39.         $entityName $event->getConfig()->get('sourceEntity');
  40.         if ($entityName !== ProductDefinition::ENTITY_NAME || empty($row['category_paths'])) {
  41.             return;
  42.         }
  43.         $result = [];
  44.         $categoriesPaths explode('|'$row['category_paths']);
  45.         $newCategoriesPayload = [];
  46.         foreach ($categoriesPaths as $path) {
  47.             $categories explode('>'$path);
  48.             $categoryId null;
  49.             foreach ($categories as $currentIndex => $categoryName) {
  50.                 if (empty($categoryName)) {
  51.                     continue;
  52.                 }
  53.                 $partialPath implode('>', \array_slice($categories0$currentIndex 1));
  54.                 if (isset($this->categoryIdCache[$partialPath])) {
  55.                     $categoryId $this->categoryIdCache[$partialPath];
  56.                     continue;
  57.                 }
  58.                 $criteria = new Criteria();
  59.                 $criteria->addFilter(new EqualsFilter('name'$categoryName));
  60.                 $criteria->addFilter(new EqualsFilter('parentId'$categoryId));
  61.                 $category $this->categoryRepository->search($criteriaContext::createDefaultContext())->first();
  62.                 if ($category === null && $categoryId === null) {
  63.                     break;
  64.                 }
  65.                 if ($category !== null) {
  66.                     $categoryId $category->getId();
  67.                     $this->categoryIdCache[$partialPath] = $categoryId;
  68.                     continue;
  69.                 }
  70.                 $parentId $categoryId;
  71.                 $categoryId Uuid::fromStringToHex($partialPath);
  72.                 $this->categoryIdCache[$partialPath] = $categoryId;
  73.                 $newCategoriesPayload[] = [
  74.                     'id' => $categoryId,
  75.                     'parent' => ['id' => $parentId],
  76.                     'name' => $categoryName,
  77.                 ];
  78.             }
  79.             if ($categoryId !== null) {
  80.                 $result[] = ['id' => $categoryId];
  81.             }
  82.         }
  83.         if (!empty($newCategoriesPayload)) {
  84.             $this->createNewCategories($newCategoriesPayload$row['category_paths']);
  85.         }
  86.         $record $event->getRecord();
  87.         $record['categories'] = !empty($record['categories']) ? array_merge($record['categories'], $result) : $result;
  88.         $event->setRecord($record);
  89.     }
  90.     private function createNewCategories(array $payloadstring $categoryPaths): void
  91.     {
  92.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  93.             $behavior = new SyncBehavior();
  94.         } else {
  95.             $behavior = new SyncBehavior(truetrue);
  96.         }
  97.         $result $this->syncService->sync([
  98.             new SyncOperation(
  99.                 'write',
  100.                 CategoryDefinition::ENTITY_NAME,
  101.                 SyncOperation::ACTION_UPSERT,
  102.                 $payload
  103.             ),
  104.         ], Context::createDefaultContext(), $behavior);
  105.         if (Feature::isActive('FEATURE_NEXT_15815')) {
  106.             // @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
  107.             return;
  108.         }
  109.         if (!$result->isSuccess()) {
  110.             $operation $result->get('write');
  111.             throw new ProcessingException(sprintf(
  112.                 'Failed writing categories for path %s with errors: %s',
  113.                 $categoryPaths,
  114.                 $operation json_encode(array_column($operation->getResult(), 'errors')) : ''
  115.             ));
  116.         }
  117.     }
  118. }