<?php
declare(strict_types=1);
namespace App\Form\EventListener\Payment;
use App\Entity\Payment\PaymentInterface;
use App\Form\FormHelper;
use App\Repository\Order\OrderRepository;
use App\Service\MoneyService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Contracts\Translation\TranslatorInterface;
class AddPaymentsFieldSubscriber extends FormHelper implements EventSubscriberInterface
{
private ?int $orderId;
public function __construct(
private OrderRepository $orderRepository,
private TranslatorInterface $translator,
private MoneyService $moneyService,
int $orderId = null,
) {
$this->orderId = $orderId;
}
public static function getSubscribedEvents(): array
{
return [FormEvents::PRE_SET_DATA => 'preSetData'];
}
public function preSetData(FormEvent $event): void
{
$choices = $disabledChoices = [];
$order = $this->orderRepository->find($this->orderId);
foreach ($order->getPayments() as $payment) {
$choices[$this->translator->trans('app.payment_method.codes.' . $payment) . ' (' . $this->moneyService->formatPrice($payment->getAmount()) . ')'] = $payment->getId();
if (PaymentInterface::STATE_PAID !== $payment->getState()) {
$disabledChoices[] = $payment->getId();
}
}
$event->getForm()->add('payments', ChoiceType::class, $this->getChoiceParameters(
'app.order.modal.cancel.label',
'app.order.modal.cancel.label',
false,
[
'choices' => $choices,
'multiple' => true,
'expanded' => true,
'choice_attr' => fn ($choice, $key, int $value) => true === \in_array($value, $disabledChoices, true) ? ['disabled' => 'disabled'] : [],
]
));
}
}