vendor/sylius/sylius/src/Sylius/Bundle/PromotionBundle/Form/Type/PromotionCouponToCodeType.php line 25

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  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 Sylius\Bundle\PromotionBundle\Form\Type;
  12. use Sylius\Component\Promotion\Model\PromotionCouponInterface;
  13. use Sylius\Component\Resource\Repository\RepositoryInterface;
  14. use Symfony\Component\Form\AbstractType;
  15. use Symfony\Component\Form\DataTransformerInterface;
  16. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  17. use Symfony\Component\Form\Extension\Core\Type\TextType;
  18. use Symfony\Component\Form\FormBuilderInterface;
  19. use Symfony\Component\OptionsResolver\OptionsResolver;
  20. final class PromotionCouponToCodeType extends AbstractType implements DataTransformerInterface
  21. {
  22.     public function __construct(private RepositoryInterface $promotionCouponRepository)
  23.     {
  24.     }
  25.     public function buildForm(FormBuilderInterface $builder, array $options): void
  26.     {
  27.         $builder->addModelTransformer($this);
  28.     }
  29.     public function transform($value): string
  30.     {
  31.         if (null === $value) {
  32.             return '';
  33.         }
  34.         if (!$value instanceof PromotionCouponInterface) {
  35.             throw new UnexpectedTypeException($valuePromotionCouponInterface::class);
  36.         }
  37.         return $value->getCode();
  38.     }
  39.     public function reverseTransform($value): ?PromotionCouponInterface
  40.     {
  41.         if (null === $value || '' === $value) {
  42.             return null;
  43.         }
  44.         return $this->promotionCouponRepository->findOneBy(['code' => $value]);
  45.     }
  46.     public function configureOptions(OptionsResolver $resolver): void
  47.     {
  48.         $resolver
  49.             ->setDefaults([
  50.                 'data_class' => null,
  51.                 'label' => 'sylius.ui.code',
  52.             ])
  53.         ;
  54.     }
  55.     public function getParent(): string
  56.     {
  57.         return TextType::class;
  58.     }
  59.     public function getBlockPrefix(): string
  60.     {
  61.         return 'sylius_promotion_coupon_to_code';
  62.     }
  63. }