Jacek Kowalski
4 hours ago 6b9278a5d57091fce636dbb640b380cfb990db6c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
declare(strict_types=1);
 
namespace App\Form;
 
use App\Enum\LabelType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
 
/**
 * @extends AbstractType<array{type: LabelType, label: string}>
 */
class AddLabelType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options): void {
        $builder
            ->add('type', EnumType::class, [
                'class' => LabelType::class,
                'label' => 'label_type_header',
                'choice_label' => static fn(LabelType $type): string => 'label_type_' . $type->value,
            ])
            ->add('label', TextType::class, [
                'label' => 'label_header',
                'constraints' => [new NotBlank(), new Length(max: 255)],
            ])
            ->add('save', SubmitType::class, ['label' => 'label_action_add']);
    }
 
    public function configureOptions(OptionsResolver $resolver): void {
        $resolver->setDefaults([
            'constraints' => [new Callback(self::validateFormat(...))],
        ]);
    }
 
    /**
     * @param array{type: ?LabelType, label: ?string} $data
     */
    public static function validateFormat(array $data, ExecutionContextInterface $context): void {
        $type = $data['type'];
 
        if ($type !== null && !$type->isValid($type->normalize((string)$data['label']))) {
            $context->buildViolation('label_invalid_number')->setTranslationDomain('messages')->atPath('[label]')->addViolation();
        }
    }
}