src/Form/EventListener/Payment/AddPaymentsFieldSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Form\EventListener\Payment;
  4. use App\Entity\Payment\PaymentInterface;
  5. use App\Form\FormHelper;
  6. use App\Repository\Order\OrderRepository;
  7. use App\Service\MoneyService;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  10. use Symfony\Component\Form\FormEvent;
  11. use Symfony\Component\Form\FormEvents;
  12. use Symfony\Contracts\Translation\TranslatorInterface;
  13. class AddPaymentsFieldSubscriber extends FormHelper implements EventSubscriberInterface
  14. {
  15.     private ?int $orderId;
  16.     public function __construct(
  17.         private OrderRepository $orderRepository,
  18.         private TranslatorInterface $translator,
  19.         private MoneyService $moneyService,
  20.         int $orderId null,
  21.     ) {
  22.         $this->orderId $orderId;
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [FormEvents::PRE_SET_DATA => 'preSetData'];
  27.     }
  28.     public function preSetData(FormEvent $event): void
  29.     {
  30.         $choices $disabledChoices = [];
  31.         $order $this->orderRepository->find($this->orderId);
  32.         foreach ($order->getPayments() as $payment) {
  33.             $choices[$this->translator->trans('app.payment_method.codes.' $payment) . ' (' $this->moneyService->formatPrice($payment->getAmount()) . ')'] = $payment->getId();
  34.             if (PaymentInterface::STATE_PAID !== $payment->getState()) {
  35.                 $disabledChoices[] = $payment->getId();
  36.             }
  37.         }
  38.         $event->getForm()->add('payments'ChoiceType::class, $this->getChoiceParameters(
  39.             'app.order.modal.cancel.label',
  40.             'app.order.modal.cancel.label',
  41.             false,
  42.             [
  43.                 'choices' => $choices,
  44.                 'multiple' => true,
  45.                 'expanded' => true,
  46.                 'choice_attr' => fn ($choice$keyint $value) => true === \in_array($value$disabledChoicestrue) ? ['disabled' => 'disabled'] : [],
  47.             ]
  48.         ));
  49.     }
  50. }