src/EventSubscriber/Geographical/AddCustomerToAddressSubscriber.php line 40

  1. <?php
  2. /*
  3.  * This file is part of the Pellipop project.
  4.  *
  5.  * (c) Mobizel
  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 App\EventSubscriber\Geographical;
  12. use ApiPlatform\Symfony\EventListener\EventPriorities;
  13. use App\Entity\Geographical\Address;
  14. use Sylius\Component\Customer\Context\CustomerContextInterface;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpKernel\Event\ViewEvent;
  18. use Symfony\Component\HttpKernel\KernelEvents;
  19. final class AddCustomerToAddressSubscriber implements EventSubscriberInterface
  20. {
  21.     private CustomerContextInterface $customerContext;
  22.     public function __construct(CustomerContextInterface $customerContext)
  23.     {
  24.         $this->customerContext $customerContext;
  25.     }
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             KernelEvents::VIEW => ['attachCustomer'EventPriorities::PRE_WRITE],
  30.         ];
  31.     }
  32.     public function attachCustomer(ViewEvent $event): void
  33.     {
  34.         /** @var Address $address */
  35.         $address $event->getControllerResult();
  36.         $method $event->getRequest()->getMethod();
  37.         if (!$address instanceof Address || Request::METHOD_POST !== $method) {
  38.             return;
  39.         }
  40.         $address->setCustomer($this->customerContext->getCustomer());
  41.     }
  42. }