1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bdf\Form\Attribute\Element; |
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 Bdf\Form\ElementBuilderInterface; |
12
|
|
|
use Bdf\Form\Transformer\TransformerInterface; |
13
|
|
|
use Nette\PhpGenerator\Literal; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Add a transformer on the element, using a transformer class |
17
|
|
|
* |
18
|
|
|
* Note: it's preferred to use directly the transformer as attribute on the element property |
19
|
|
|
* |
20
|
|
|
* This attribute is equivalent to call : |
21
|
|
|
* <code> |
22
|
|
|
* $builder->string('foo')->transformer(new MyTransformer(...$arguments)); |
23
|
|
|
* </code> |
24
|
|
|
* |
25
|
|
|
* Usage: |
26
|
|
|
* <code> |
27
|
|
|
* class MyForm extends AttributeForm |
28
|
|
|
* { |
29
|
|
|
* #[Transformer(MyTransformer::class, ['foo', 'bar'])] |
30
|
|
|
* private IntegerElement $foo; |
31
|
|
|
* } |
32
|
|
|
* </code> |
33
|
|
|
* |
34
|
|
|
* @implements ChildBuilderAttributeInterface<\Bdf\Form\ElementBuilderInterface> |
35
|
|
|
* |
36
|
|
|
* @see ElementBuilderInterface::transformer() The called method |
37
|
|
|
* @see CallbackTransformer For use custom methods as transformer instead of class |
38
|
|
|
*/ |
39
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] |
40
|
|
|
class Transformer implements ChildBuilderAttributeInterface |
41
|
|
|
{ |
42
|
3 |
|
public function __construct( |
43
|
|
|
/** |
44
|
|
|
* The transformer class name |
45
|
|
|
* |
46
|
|
|
* @var class-string<TransformerInterface> |
47
|
|
|
* @readonly |
48
|
|
|
*/ |
49
|
|
|
private string $transformerClass, |
50
|
|
|
/** |
51
|
|
|
* Arguments to provide on the transformer constructor |
52
|
|
|
* |
53
|
|
|
* @var array |
54
|
|
|
* @readonly |
55
|
|
|
*/ |
56
|
|
|
private array $constructorArguments = [], |
57
|
|
|
) { |
58
|
3 |
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* {@inheritdoc} |
62
|
|
|
*/ |
63
|
1 |
|
public function applyOnChildBuilder(AttributeForm $form, ChildBuilderInterface $builder): void |
64
|
|
|
{ |
65
|
1 |
|
$builder->transformer(new $this->transformerClass(...$this->constructorArguments)); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* {@inheritdoc} |
70
|
|
|
*/ |
71
|
2 |
|
public function generateCodeForChildBuilder(string $name, AttributesProcessorGenerator $generator, AttributeForm $form): void |
72
|
|
|
{ |
73
|
2 |
|
$transformer = $generator->useAndSimplifyType($this->transformerClass); |
74
|
2 |
|
$generator->line('$?->transformer(new ?(...?));', [$name, new Literal($transformer), $this->constructorArguments]); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|