src/EventSubscriber/Order/OrderCheckoutSubscriber.php line 33

  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\Order;
  12. use App\Entity\Customer\Customer;
  13. use App\Entity\Order\Order;
  14. use App\Generator\Order\OrderNumberGeneratorInterface;
  15. use App\OrderProductionStates;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Component\Workflow\Event\Event;
  18. use Symfony\Component\Workflow\WorkflowInterface;
  19. use Webmozart\Assert\Assert;
  20. class OrderCheckoutSubscriber implements EventSubscriberInterface
  21. {
  22.     public function __construct(
  23.         private OrderNumberGeneratorInterface $orderNumberGenerator,
  24.         private WorkflowInterface $orderProductionStateMachine,
  25.     ) {
  26.     }
  27.     public function onEnter(Event $event)
  28.     {
  29.         /** @var Order $order */
  30.         $order $event->getSubject();
  31.         Assert::isInstanceOf($orderOrder::class);
  32.         /** @var Customer $customer */
  33.         $customer $order->getCustomer();
  34.         Assert::notNull($customer'Can not create order without customer');
  35.         // When order was paid by Stripe (direct or complement), do not check/debit credits
  36.         if (!$order->isDirectPayment()) {
  37.             Assert::greaterThanEq(
  38.                 ($customer->getCredits() - $order->getTotal()),
  39.                 0,
  40.                 'Not enough customer credits to decrease for order.',
  41.             );
  42.             $customer->setCredits($customer->getCredits() - $order->getTotal());
  43.         }
  44.         $order->setCheckoutCompletedAt(new \DateTimeImmutable());
  45.         $order->setNumber($this->orderNumberGenerator->generate($order));
  46.         $this->orderProductionStateMachine->apply($orderOrderProductionStates::TRANSITION_CUSTOMER_DOWLOAD);
  47.     }
  48.     public static function getSubscribedEvents()
  49.     {
  50.         return [
  51.             'workflow.order.enter.in_production' => 'onEnter',
  52.         ];
  53.     }
  54. }