-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsArrayConstraint.php
More file actions
91 lines (86 loc) · 2.6 KB
/
AsArrayConstraint.php
File metadata and controls
91 lines (86 loc) · 2.6 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace Bdf\Form\Attribute\Aggregate;
use Attribute;
use Bdf\Form\Aggregate\ArrayElementBuilder;
use Bdf\Form\Attribute\ChildBuilderAttributeInterface;
use Bdf\Form\Attribute\Processor\MethodChildBuilderAttributeInterface;
use Bdf\Form\Constraint\Closure;
use ReflectionMethod;
use Symfony\Component\Validator\Constraint;
/**
* Define the annotated method as a custom constraint for an array element
*
* Its prototype should be :
* `public function ($value, ElementInterface $input): bool|string|array{code: string message: string}|null`
*
* - Return true, or null (nothing) for a valid input
* - Return false for invalid input, with the default error message (or the declared one)
* - Return string for a custom error message
* - Return array with error message and code
*
* This attribute is equivalent to call :
* <code>
* $builder->array('foo')->arrayConstraint([$this, 'validateFoo'], 'Foo is invalid');
* </code>
*
* Usage:
* <code>
* class MyForm extends AttributeForm
* {
* private ArrayElement $foo;
*
* #[AsArrayConstraint('foo', message: 'Foo is invalid')]
* public function validateFoo(array $value, ElementInterface $input): bool
* {
* return count($value) % 5 > 2;
* }
* }
* </code>
*
* @see ArrayElementBuilder::arrayConstraint() The called method
* @see Constraint
* @see Closure The used constraint
* @see ArrayConstraint Use for a class constraint
* @see CallbackArrayConstraint To annotate the property instead of the method
*
* @implements MethodChildBuilderAttributeInterface<ArrayElementBuilder>
*
* @api
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
final class AsArrayConstraint implements MethodChildBuilderAttributeInterface
{
public function __construct(
/**
* The element property name to which the constraint is applied
*
* @var non-empty-string
* @readonly
*/
private string $target,
/**
* The error message to use
* This option is used only if the validator return false, in other cases,
* the message returned by the validator will be used
*
* @var string|null
* @readonly
*/
private ?string $message = null,
) {
}
/**
* {@inheritdoc}
*/
public function targetElements(): array
{
return [$this->target];
}
/**
* {@inheritdoc}
*/
public function attribute(ReflectionMethod $method): ChildBuilderAttributeInterface
{
return new CallbackArrayConstraint($method->getName(), $this->message);
}
}