|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file has been created by developers from BitBag. |
| 5 | + * Feel free to contact us once you face any issues or want to start |
| 6 | + * You can find more information about us on https://bitbag.io and write us |
| 7 | + * an email on hello@bitbag.io. |
| 8 | + */ |
| 9 | + |
| 10 | +declare(strict_types=1); |
| 11 | + |
| 12 | +namespace BitBag\SyliusUserComPlugin\EventSubscriber; |
| 13 | + |
| 14 | +use BitBag\SyliusUserComPlugin\Manager\CustomerUpdateManagerInterface; |
| 15 | +use Sylius\Component\Core\Model\CustomerInterface; |
| 16 | +use Sylius\Component\Core\Model\OrderInterface; |
| 17 | +use Symfony\Component\Form\FormEvent; |
| 18 | +use Symfony\Component\Form\FormEvents; |
| 19 | + |
| 20 | +final class CustomerProfileUpdatedSubscriber implements CustomerProfileUpdatedSubscriberInterface |
| 21 | +{ |
| 22 | + private const EVENTS = [ |
| 23 | + FormEvents::POST_SUBMIT => 'postCustomerProfileUpdated', |
| 24 | + ]; |
| 25 | + |
| 26 | + public function __construct( |
| 27 | + private readonly CustomerUpdateManagerInterface $customerUpdateManager, |
| 28 | + ) { |
| 29 | + } |
| 30 | + |
| 31 | + public function postCustomerProfileUpdated(FormEvent $event): void |
| 32 | + { |
| 33 | + $formName = $event->getForm()->getName(); |
| 34 | + |
| 35 | + $eventName = array_key_exists($formName, self::FORM_NAME_TO_EVENT_MAP) |
| 36 | + ? self::FORM_NAME_TO_EVENT_MAP[$formName] |
| 37 | + : self::DEFAULT_EVENT |
| 38 | + ; |
| 39 | + |
| 40 | + $subject = $event->getData(); |
| 41 | + |
| 42 | + if ($subject instanceof CustomerInterface) { |
| 43 | + $this->customerUpdateManager->manageChange( |
| 44 | + $eventName, |
| 45 | + $subject, |
| 46 | + $subject->getDefaultAddress(), |
| 47 | + $subject->getEmail(), |
| 48 | + ); |
| 49 | + |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if ($subject instanceof OrderInterface) { |
| 54 | + $customer = $subject->getCustomer(); |
| 55 | + if (null !== $customer && !$customer instanceof CustomerInterface) { |
| 56 | + throw new \RuntimeException('Customer is not set or is not an instance of CustomerInterface'); |
| 57 | + } |
| 58 | + $this->customerUpdateManager->manageChange( |
| 59 | + $eventName, |
| 60 | + $customer, |
| 61 | + $subject->getShippingAddress(), |
| 62 | + $customer?->getEmail(), |
| 63 | + ); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + public static function getSubscribedEvents(): array |
| 68 | + { |
| 69 | + return self::EVENTS; |
| 70 | + } |
| 71 | +} |
0 commit comments