src/Module/Checkout/Subscriber/FinishSubscriber.php line 46

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Module\Checkout\Subscriber;
  4. use App\Module\Checkout\Provider\DeniosCustomerProviderInterface;
  5. use App\Module\ShortSimpleCheckout\Event\View\FinishDispatchEvent;
  6. use App\Module\ShortSimpleCheckout\Events;
  7. use Commercetools\Core\Model\Order\Order;
  8. use Denios\Data\Customer\AnonymousCustomerOrderData;
  9. use JsonException;
  10. use RuntimeException;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. /**
  13. * @package App\Module\Checkout\Subscriber
  14. */
  15. class FinishSubscriber implements EventSubscriberInterface
  16. {
  17. private DeniosCustomerProviderInterface $customerProvider;
  18. /**
  19. * @param DeniosCustomerProviderInterface $customerProvider
  20. */
  21. public function __construct(
  22. DeniosCustomerProviderInterface $customerProvider
  23. ) {
  24. $this->customerProvider = $customerProvider;
  25. }
  26. /**
  27. * @return array
  28. */
  29. public static function getSubscribedEvents(): array
  30. {
  31. return [
  32. Events::FINISH_INDEX_DISPATCH => 'addCustomerToView'
  33. ];
  34. }
  35. /**
  36. * @param FinishDispatchEvent $event
  37. * @return void
  38. */
  39. public function addCustomerToView(FinishDispatchEvent $event): void
  40. {
  41. $anonymousCustomerOrderData = $this->getAnonymousCustomerOrderData($event->getOrder());
  42. $event->replaceVariable('customer', $this->customerProvider->getCustomer($anonymousCustomerOrderData));
  43. }
  44. /**
  45. * @param Order $order
  46. * @return AnonymousCustomerOrderData|null
  47. * @throws JsonException
  48. */
  49. private function getAnonymousCustomerOrderData(Order $order): ?AnonymousCustomerOrderData
  50. {
  51. $custom = $order->getCustom();
  52. if ($custom === null) {
  53. throw new RuntimeException('$custom is unexpected NULL.');
  54. }
  55. $fields = $custom->getFields();
  56. if ($fields === null) {
  57. throw new RuntimeException('$fields is unexpected NULL.');
  58. }
  59. if (!$fields->hasField('anonymousData')) {
  60. return null;
  61. }
  62. return AnonymousCustomerOrderData::fromJson($fields->getFieldAsString('anonymousData'));
  63. }
  64. }