vendor/shopware/administration/System/SalesChannel/Subscriber/SalesChannelUserConfigSubscriber.php line 34

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Administration\System\SalesChannel\Subscriber;
  3. use Shopware\Core\Framework\Context;
  4. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityDeletedEvent;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  8. use Shopware\Core\System\User\Aggregate\UserConfig\UserConfigCollection;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class SalesChannelUserConfigSubscriber implements EventSubscriberInterface
  11. {
  12.     public const CONFIG_KEY 'sales-channel-favorites';
  13.     private EntityRepository $userConfigRepository;
  14.     /**
  15.      * @internal
  16.      */
  17.     public function __construct(EntityRepository $userConfigRepository)
  18.     {
  19.         $this->userConfigRepository $userConfigRepository;
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             'sales_channel.deleted' => 'onSalesChannelDeleted',
  25.         ];
  26.     }
  27.     public function onSalesChannelDeleted(EntityDeletedEvent $deletedEvent): void
  28.     {
  29.         $context $deletedEvent->getContext();
  30.         $deletedSalesChannelIds $deletedEvent->getIds();
  31.         $writeUserConfigs = [];
  32.         foreach ($this->getAllFavoriteUserConfigs($context) as $userConfigEntity) {
  33.             $salesChannelIds $userConfigEntity->getValue();
  34.             if ($salesChannelIds === null) {
  35.                 continue;
  36.             }
  37.             // Find matching IDs
  38.             $matchingIds array_intersect($deletedSalesChannelIds$salesChannelIds);
  39.             if (!$matchingIds) {
  40.                 continue;
  41.             }
  42.             // Removes the IDs from $matchingIds from the array
  43.             $newUserConfigArray array_diff($salesChannelIds$matchingIds);
  44.             $writeUserConfigs[] = [
  45.                 'id' => $userConfigEntity->getId(),
  46.                 'value' => array_values($newUserConfigArray),
  47.             ];
  48.         }
  49.         $this->userConfigRepository->upsert($writeUserConfigs$context);
  50.     }
  51.     private function getAllFavoriteUserConfigs(Context $context): UserConfigCollection
  52.     {
  53.         $criteria = new Criteria();
  54.         $criteria->addFilter(new EqualsFilter('key'self::CONFIG_KEY));
  55.         /** @var UserConfigCollection $result */
  56.         $result $this->userConfigRepository->search($criteria$context)->getEntities();
  57.         return $result;
  58.     }
  59. }