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.     /** @var RepositoryInterface */
  23.     private $promotionCouponRepository;
  24.     public function __construct(RepositoryInterface $promotionCouponRepository)
  25.     {
  26.         $this->promotionCouponRepository $promotionCouponRepository;
  27.     }
  28.     public function buildForm(FormBuilderInterface $builder, array $options): void
  29.     {
  30.         $builder->addModelTransformer($this);
  31.     }
  32.     public function transform($coupon): string
  33.     {
  34.         if (null === $coupon) {
  35.             return '';
  36.         }
  37.         if (!$coupon instanceof PromotionCouponInterface) {
  38.             throw new UnexpectedTypeException($couponPromotionCouponInterface::class);
  39.         }
  40.         return $coupon->getCode();
  41.     }
  42.     public function reverseTransform($code): ?PromotionCouponInterface
  43.     {
  44.         if (null === $code || '' === $code) {
  45.             return null;
  46.         }
  47.         return $this->promotionCouponRepository->findOneBy(['code' => $code]);
  48.     }
  49.     public function configureOptions(OptionsResolver $resolver): void
  50.     {
  51.         $resolver
  52.             ->setDefaults([
  53.                 'data_class' => null,
  54.                 'label' => 'sylius.ui.code',
  55.             ])
  56.         ;
  57.     }
  58.     public function getParent(): string
  59.     {
  60.         return TextType::class;
  61.     }
  62.     public function getBlockPrefix(): string
  63.     {
  64.         return 'sylius_promotion_coupon_to_code';
  65.     }
  66. }