<?php
/**
* Discount Order Type
*
* @author Bertin van den Ham <b.vandenham@dappr.nl>
*/
namespace VisualMedia\DiscountBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Contracts\EventDispatcher\Event;
use VisualMedia\DiscountBundle\Entity\Discount;
use VisualMedia\DiscountBundle\Form\Constraint\DiscountValidConstraint;
use VisualMedia\DiscountBundle\Model\DiscountModel;
use VisualMedia\LisaBundle\Form\Type\BooleanType;
use VisualMedia\LisaBundle\Form\Type\DateTimeType;
use VisualMedia\OrderBundle\Entity\BaseOrder;
use function GuzzleHttp\Psr7\parse_header;
/**
* Discount Order Type
*/
class DiscountOrderType extends AbstractType
{
public const NAME = 'discount_order';
public const DISCOUNT_NAME = 'discount';
public const DISCOUNT_CODE = 'code';
public const DISCOUNT_CHECK_CODE = 'checkCode';
public const DISCOUNT_REMOVE_CODE = 'removeCode';
/**
* {@inheritDoc}
*/
public function getName(): string
{
return static::NAME;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($options) {
$form = $event->getForm();
if (null === $order = $options['order']) {
return;
}
$this->discountOrderFormModifier($form, $order, FormEvents::PRE_SET_DATA);
});
}
/**
* @param FormInterface $form
* @param BaseOrder $order
* @param string|null $formEvent
* @param void
*/
protected function discountOrderFormModifier(FormInterface $form, BaseOrder $order, string $formEvent = null): void
{
if ($order->getDiscount() === null) {
$form->add(static::DISCOUNT_CODE, TextType::class, [
'label' => 'discount_order.code',
'required' => false,
'constraints' => $this->discountCodeFieldConstraints()
]);
$form->add(static::DISCOUNT_CHECK_CODE, SubmitType::class, [
'label' => 'discount_order.checkCode'
]);
}
else {
$form->add(static::DISCOUNT_REMOVE_CODE, SubmitType::class, [
'label' => 'x'
]);
}
}
/**
* Return a array of Contraints for the discount order field
* this function could be used to add extra custom Constraints for App
* specific code.
* @return array|
*/
protected function discountCodeFieldConstraints(): array
{
return [
new DiscountValidConstraint(),
];
}
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'order' => null
]);
}
}