<?php
/*
* This file is part of ProductSort
*
* Copyright(c) Akira Kurozumi <info@a-zumi.net>
*
* https://a-zumi.net
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Plugin\ProductSort42;
use Doctrine\ORM\EntityManagerInterface;
use Eccube\Entity\Product;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Event\TemplateEvent;
use Plugin\ProductSort42\Entity\Config;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class Event implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
'@admin/Product/index.twig' => 'onRenderAdminProduct',
EccubeEvents::ADMIN_PRODUCT_EDIT_COMPLETE => 'onUpdateProductSortNo',
EccubeEvents::ADMIN_PRODUCT_COPY_COMPLETE => 'onUpdateProductSortNo',
];
}
/**
* @param TemplateEvent $event
*
* @return void
*/
public function onRenderAdminProduct(TemplateEvent $event): void
{
if (false === $this->isEnabled()) {
return;
}
$event->addSnippet('@ProductSort42/admin/Product/index.twig');
}
/**
* 新規商品登録(複製含む)が完了時にplg_sort_noを再設定
*
* @param EventArgs $eventArgs
*
* @return void
*/
public function onUpdateProductSortNo(EventArgs $eventArgs): void
{
if (false === $this->isEnabled()) {
return;
}
$productRepository = $this->entityManager->getRepository(Product::class);
$Products = $productRepository->findBy([], ['plg_sort_no' => 'ASC']);
foreach ($Products as $key => $Product) {
$Product->setPlgSortNo($key + 1);
$this->entityManager->persist($Product);
}
$this->entityManager->flush();
}
/**
* @return bool
*/
private function isEnabled(): bool
{
$Config = $this->entityManager->find(Config::class, Config::ID);
return $Config && $Config->isEnable();
}
}