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

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