src/Administration/System/SalesChannel/Subscriber/SalesChannelUserConfigSubscriber.php line 36

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