app/Plugin/ProductSort42/Event.php line 53

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of ProductSort
  4.  *
  5.  * Copyright(c) Akira Kurozumi <info@a-zumi.net>
  6.  *
  7.  * https://a-zumi.net
  8.  *
  9.  * For the full copyright and license information, please view the LICENSE
  10.  * file that was distributed with this source code.
  11.  */
  12. namespace Plugin\ProductSort42;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Eccube\Entity\Product;
  15. use Eccube\Event\EccubeEvents;
  16. use Eccube\Event\EventArgs;
  17. use Eccube\Event\TemplateEvent;
  18. use Plugin\ProductSort42\Entity\Config;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. class Event implements EventSubscriberInterface
  21. {
  22.     /**
  23.      * @var EntityManagerInterface
  24.      */
  25.     private EntityManagerInterface $entityManager;
  26.     public function __construct(EntityManagerInterface $entityManager)
  27.     {
  28.         $this->entityManager $entityManager;
  29.     }
  30.     /**
  31.      * @return string[]
  32.      */
  33.     public static function getSubscribedEvents(): array
  34.     {
  35.         return [
  36.             '@admin/Product/index.twig' => 'onRenderAdminProduct',
  37.             EccubeEvents::ADMIN_PRODUCT_EDIT_COMPLETE => 'onUpdateProductSortNo',
  38.             EccubeEvents::ADMIN_PRODUCT_COPY_COMPLETE => 'onUpdateProductSortNo',
  39.         ];
  40.     }
  41.     /**
  42.      * @param TemplateEvent $event
  43.      *
  44.      * @return void
  45.      */
  46.     public function onRenderAdminProduct(TemplateEvent $event): void
  47.     {
  48.         if (false === $this->isEnabled()) {
  49.             return;
  50.         }
  51.         $event->addSnippet('@ProductSort42/admin/Product/index.twig');
  52.     }
  53.     /**
  54.      * 新規商品登録(複製含む)が完了時にplg_sort_noを再設定
  55.      *
  56.      * @param EventArgs $eventArgs
  57.      *
  58.      * @return void
  59.      */
  60.     public function onUpdateProductSortNo(EventArgs $eventArgs): void
  61.     {
  62.         if (false === $this->isEnabled()) {
  63.             return;
  64.         }
  65.         $productRepository $this->entityManager->getRepository(Product::class);
  66.         $Products $productRepository->findBy([], ['plg_sort_no' => 'ASC']);
  67.         foreach ($Products as $key => $Product) {
  68.             $Product->setPlgSortNo($key 1);
  69.             $this->entityManager->persist($Product);
  70.         }
  71.         $this->entityManager->flush();
  72.     }
  73.     /**
  74.      * @return bool
  75.      */
  76.     private function isEnabled(): bool
  77.     {
  78.         $Config $this->entityManager->find(Config::class, Config::ID);
  79.         return $Config && $Config->isEnable();
  80.     }
  81. }