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

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.     private SlugGeneratorInterface $slugGenerator;
  24.     public function __construct(SlugGeneratorInterface $slugGenerator)
  25.     {
  26.         $this->slugGenerator $slugGenerator;
  27.     }
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             KernelEvents::VIEW => ['generateSlug'EventPriorities::PRE_VALIDATE],
  32.         ];
  33.     }
  34.     public function generateSlug(ViewEvent $event): void
  35.     {
  36.         $product $event->getControllerResult();
  37.         $method $event->getRequest()->getMethod();
  38.         if (
  39.             !$product instanceof ProductInterface ||
  40.             !in_array($method, [Request::METHOD_POSTRequest::METHOD_PUT], true)
  41.         ) {
  42.             return;
  43.         }
  44.         /** @var ProductTranslationInterface $productTranslation */
  45.         foreach ($product->getTranslations() as $productTranslation) {
  46.             if ($productTranslation->getSlug() !== null && $productTranslation->getSlug() !== '') {
  47.                 continue;
  48.             }
  49.             if ($productTranslation->getName() === null || $productTranslation->getName() === '') {
  50.                 continue;
  51.             }
  52.             $productTranslation->setSlug($this->slugGenerator->generate($productTranslation->getName()));
  53.         }
  54.         $event->setControllerResult($product);
  55.     }
  56. }