ArrayConstraint   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 37
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A generateCodeForChildBuilder() 0 5 1
A __construct() 0 16 1
A applyOnChildBuilder() 0 3 1
1
<?php
2
3
namespace Bdf\Form\Attribute\Aggregate;
4
5
use Attribute;
6
use Bdf\Form\Aggregate\ArrayElementBuilder;
7
use Bdf\Form\Attribute\AttributeForm;
8
use Bdf\Form\Attribute\ChildBuilderAttributeInterface;
9
use Bdf\Form\Attribute\Constraint\Satisfy;
10
use Bdf\Form\Attribute\Processor\CodeGenerator\AttributesProcessorGenerator;
11
use Bdf\Form\Attribute\Processor\GenerateConfiguratorStrategy;
12
use Bdf\Form\Child\ChildBuilderInterface;
13
use Nette\PhpGenerator\Literal;
14
use Symfony\Component\Validator\Constraint;
15
16
/**
17
 * Add a constraint on the whole array element
18
 * Use Satisfy, or directly the constraint as attribute for add a constraint on one array item
19
 *
20
 * This attribute is equivalent to call :
21
 * <code>
22
 * $builder->array('values')->arrayConstraints(MyConstraint::class, $options);
23
 * </code>
24
 *
25
 * Usage:
26
 * <code>
27
 * class MyForm extends AttributeForm
28
 * {
29
 *     #[ArrayConstraint(Unique::class, ['message' => 'My error'])]
30
 *     private ArrayElement $values;
31
 * }
32
 * </code>
33
 *
34
 * @see Satisfy Attribute for add constraint for items
35
 * @see ArrayElementBuilder::arrayConstraint() The called method
36
 * @see CallbackArrayConstraint Use for a custom method validation
37
 *
38
 * @implements ChildBuilderAttributeInterface<ArrayElementBuilder>
39
 */
40
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
41
final class ArrayConstraint implements ChildBuilderAttributeInterface
42
{
43 3
    public function __construct(
44
        /**
45
         * The constraint class name
46
         *
47
         * @var class-string<Constraint>
48
         * @readonly
49
         */
50
        private string $constraint,
51
        /**
52
         * Constraint's constructor options
53
         *
54
         * @var mixed|null
55
         * @readonly
56
         */
57
        private mixed $options = null
58
    ) {
59 3
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64 1
    public function applyOnChildBuilder(AttributeForm $form, ChildBuilderInterface $builder): void
65
    {
66 1
        $builder->arrayConstraint($this->constraint, $this->options);
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 2
    public function generateCodeForChildBuilder(string $name, AttributesProcessorGenerator $generator, AttributeForm $form): void
73
    {
74 2
        $constraint = $generator->useAndSimplifyType($this->constraint);
75
76 2
        $generator->line('$?->arrayConstraint(?::class, ?);', [$name, new Literal($constraint), $this->options]);
77
    }
78
}
79