|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace SumoCoders\FrameworkCoreBundle\Form\Type; |
| 4 | + |
| 5 | +use SumoCoders\FrameworkCoreBundle\Intl\BelgiumPostCodes; |
| 6 | +use SumoCoders\FrameworkCoreBundle\ValueObject\BelgiumPostCode; |
| 7 | +use Symfony\Component\Form\AbstractType; |
| 8 | +use Symfony\Component\Form\CallbackTransformer; |
| 9 | +use Symfony\Component\Form\ChoiceList\ChoiceList; |
| 10 | +use Symfony\Component\Form\ChoiceList\Loader\IntlCallbackChoiceLoader; |
| 11 | +use Symfony\Component\Form\Exception\LogicException; |
| 12 | +use Symfony\Component\Form\Extension\Core\Type\ChoiceType; |
| 13 | +use Symfony\Component\Form\FormBuilderInterface; |
| 14 | +use Symfony\Component\Intl\Intl; |
| 15 | +use Symfony\Component\OptionsResolver\Options; |
| 16 | +use Symfony\Component\OptionsResolver\OptionsResolver; |
| 17 | + |
| 18 | +class BelgiumPostCodeType extends AbstractType |
| 19 | +{ |
| 20 | + public function buildForm(FormBuilderInterface $builder, array $options): void |
| 21 | + { |
| 22 | + $builder->addModelTransformer( |
| 23 | + new CallbackTransformer( |
| 24 | + function (?BelgiumPostCode $object): ?string { |
| 25 | + return $object ? ($object->postcode . '|' . $object->municipality) : null; |
| 26 | + }, |
| 27 | + function (?string $postcodeKey): ?BelgiumPostCode { |
| 28 | + if ($postcodeKey === null || $postcodeKey === '') { |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + [$postcode, $municipality] = explode('|', $postcodeKey, 2); |
| 33 | + return new BelgiumPostCode( |
| 34 | + $postcode, |
| 35 | + $municipality |
| 36 | + ); |
| 37 | + } |
| 38 | + ) |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + public function configureOptions(OptionsResolver $resolver): void |
| 43 | + { |
| 44 | + $resolver->setDefaults([ |
| 45 | + 'choice_loader' => function (Options $options) { |
| 46 | + if (!class_exists(Intl::class)) { |
| 47 | + throw new LogicException(sprintf('The "symfony/intl" component is required to use "%s". Try running "composer require symfony/intl".', static::class)); // phpcs:ignore Generic.Files.LineLength |
| 48 | + } |
| 49 | + |
| 50 | + return ChoiceList::loader( |
| 51 | + $this, |
| 52 | + new IntlCallbackChoiceLoader(static fn() => array_flip(BelgiumPostCodes::getNames())) |
| 53 | + ); |
| 54 | + }, |
| 55 | + 'choice_translation_domain' => false, |
| 56 | + 'invalid_message' => 'Please select a valid postcode.', |
| 57 | + 'placeholder' => '', |
| 58 | + 'autocomplete' => true, |
| 59 | + 'label' => 'Postcode and municipality', |
| 60 | + ]); |
| 61 | + } |
| 62 | + |
| 63 | + public function getParent(): ?string |
| 64 | + { |
| 65 | + return ChoiceType::class; |
| 66 | + } |
| 67 | + |
| 68 | + public function getBlockPrefix(): string |
| 69 | + { |
| 70 | + return 'sumoBelgiumPostCode'; |
| 71 | + } |
| 72 | +} |
0 commit comments