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

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