-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsTransformer.php
More file actions
82 lines (76 loc) · 2.23 KB
/
AsTransformer.php
File metadata and controls
82 lines (76 loc) · 2.23 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
<?php
namespace Bdf\Form\Attribute\Element;
use Attribute;
use Bdf\Form\Attribute\Child\AsModelTransformer;
use Bdf\Form\Attribute\ChildBuilderAttributeInterface;
use Bdf\Form\Attribute\Processor\MethodChildBuilderAttributeInterface;
use Bdf\Form\ElementBuilderInterface;
use ReflectionMethod;
/**
* Define the annotated method as a transformer for elements
*
* The method should have the following signature :
* `function (mixed $value, IntegerElement $input, bool $toPhp): mixed`
*
* The `$toPhp` parameter is a boolean that indicates if the transformation is from the http value to php input value (true)
* or from the php input value to the http value (false)
*
* This attribute is equivalent to call :
* <code>
* $builder->string('foo')->transformer([$this, 'myTransformer']);
* </code>
*
* Usage:
* <code>
* class MyForm extends AttributeForm
* {
* private IntegerElement $bar;
*
* #[AsTransformer('bar')]
* public function barTransformer($value, IntegerElement $input, bool $toPhp)
* {
* return $toPhp ? hexdec($value) : dechex($value);
* }
* }
* </code>
*
* @implements MethodChildBuilderAttributeInterface<\Bdf\Form\ElementBuilderInterface>
*
* @see ElementBuilderInterface::transformer() The called method
* @see Transformer For use a transformer class as transformer
* @see AsModelTransformer For use transformer in same way, but for model transformer intead of http one
* @see CallbackTransformer To annotate the property instead
*
* @api
*/
#[Attribute(Attribute::TARGET_METHOD)]
final class AsTransformer implements MethodChildBuilderAttributeInterface
{
/**
* @var list<non-empty-string>
* @readonly
*/
private array $targets;
/**
* @param non-empty-string ...$targets Target elements properties names
* @no-named-arguments
*/
public function __construct(string ...$targets)
{
$this->targets = $targets;
}
/**
* {@inheritdoc}
*/
public function targetElements(): array
{
return $this->targets;
}
/**
* {@inheritdoc}
*/
public function attribute(ReflectionMethod $method): ChildBuilderAttributeInterface
{
return new CallbackTransformer($method->getName());
}
}