1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bdf\Form\Attribute\Constraint; |
4
|
|
|
|
5
|
|
|
use Attribute; |
6
|
|
|
use Bdf\Form\Attribute\AttributeForm; |
7
|
|
|
use Bdf\Form\Attribute\ChildBuilderAttributeInterface; |
8
|
|
|
use Bdf\Form\Attribute\Processor\CodeGenerator\AttributesProcessorGenerator; |
9
|
|
|
use Bdf\Form\Attribute\Processor\GenerateConfiguratorStrategy; |
10
|
|
|
use Bdf\Form\Child\ChildBuilderInterface; |
11
|
|
|
use Nette\PhpGenerator\Literal; |
12
|
|
|
use Symfony\Component\Validator\Constraint; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Define a custom constraint for an element, using a validation method |
16
|
|
|
* |
17
|
|
|
* Note: prefer use directly the constraint as attribute |
18
|
|
|
* |
19
|
|
|
* This attribute is equivalent to call : |
20
|
|
|
* <code> |
21
|
|
|
* $builder->integer('foo')->satisfy(MyConstraint::class, $options); |
22
|
|
|
* </code> |
23
|
|
|
* |
24
|
|
|
* Usage: |
25
|
|
|
* <code> |
26
|
|
|
* class MyForm extends AttributeForm |
27
|
|
|
* { |
28
|
|
|
* #[Satisfy(MyConstraint::class, ['foo' => 'bar'])] |
29
|
|
|
* private IntegerElement $foo; |
30
|
|
|
* } |
31
|
|
|
* </code> |
32
|
|
|
* |
33
|
|
|
* @implements ChildBuilderAttributeInterface<\Bdf\Form\ElementBuilderInterface> |
34
|
|
|
* |
35
|
|
|
* @see ElementBuilderInterface::satisfy() The called method |
36
|
|
|
* @see Constraint |
37
|
|
|
*/ |
38
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] |
39
|
|
|
class Satisfy implements ChildBuilderAttributeInterface |
40
|
|
|
{ |
41
|
3 |
|
public function __construct( |
42
|
|
|
/** |
43
|
|
|
* The constraint class name |
44
|
|
|
* |
45
|
|
|
* @var class-string<Constraint> |
46
|
|
|
* @readonly |
47
|
|
|
*/ |
48
|
|
|
private string $constraint, |
49
|
|
|
/** |
50
|
|
|
* Constraint's constructor options |
51
|
|
|
* |
52
|
|
|
* @var array|null|string |
53
|
|
|
* @readonly |
54
|
|
|
*/ |
55
|
|
|
private mixed $options = null |
56
|
|
|
) { |
57
|
3 |
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* {@inheritdoc} |
61
|
|
|
*/ |
62
|
1 |
|
public function applyOnChildBuilder(AttributeForm $form, ChildBuilderInterface $builder): void |
63
|
|
|
{ |
64
|
1 |
|
$builder->satisfy($this->constraint, $this->options); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* {@inheritdoc} |
69
|
|
|
*/ |
70
|
2 |
|
public function generateCodeForChildBuilder(string $name, AttributesProcessorGenerator $generator, AttributeForm $form): void |
71
|
|
|
{ |
72
|
2 |
|
$type = $generator->useAndSimplifyType($this->constraint); |
73
|
2 |
|
$generator->line('$?->satisfy(?::class, ?);', [$name, new Literal($type), $this->options]); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|