vendor/sylius/sylius/src/Sylius/Bundle/ApiBundle/EventSubscriber/ProductSlugEventSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace Sylius\Bundle\ApiBundle\EventSubscriber;
  12. use ApiPlatform\Core\EventListener\EventPriorities;
  13. use Sylius\Component\Core\Model\ProductInterface;
  14. use Sylius\Component\Core\Model\ProductTranslationInterface;
  15. use Sylius\Component\Product\Generator\SlugGeneratorInterface;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpKernel\Event\ViewEvent;
  19. use Symfony\Component\HttpKernel\KernelEvents;
  20. /** @experimental */
  21. final class ProductSlugEventSubscriber implements EventSubscriberInterface
  22. {
  23.     /** @var SlugGeneratorInterface */
  24.     private $slugGenerator;
  25.     public function __construct(SlugGeneratorInterface $slugGenerator)
  26.     {
  27.         $this->slugGenerator $slugGenerator;
  28.     }
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             KernelEvents::VIEW => ['generateSlug'EventPriorities::PRE_VALIDATE],
  33.         ];
  34.     }
  35.     public function generateSlug(ViewEvent $event): void
  36.     {
  37.         $product $event->getControllerResult();
  38.         $method $event->getRequest()->getMethod();
  39.         if (
  40.             !$product instanceof ProductInterface ||
  41.             !in_array($method, [Request::METHOD_POSTRequest::METHOD_PUT], true)
  42.         ) {
  43.             return;
  44.         }
  45.         /** @var ProductTranslationInterface $productTranslation */
  46.         foreach ($product->getTranslations() as $productTranslation) {
  47.             if ($productTranslation->getSlug() !== null && $productTranslation->getSlug() !== '') {
  48.                 continue;
  49.             }
  50.             if ($productTranslation->getName() === null || $productTranslation->getName() === '') {
  51.                 continue;
  52.             }
  53.             $productTranslation->setSlug($this->slugGenerator->generate($productTranslation->getName()));
  54.         }
  55.         $event->setControllerResult($product);
  56.     }
  57. }