|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bdf\Form\PropertyAccess; |
|
4
|
|
|
|
|
5
|
|
|
use Attribute; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Set the property value using the element value |
|
9
|
|
|
* |
|
10
|
|
|
* <code> |
|
11
|
|
|
* // Use the child name as property name |
|
12
|
|
|
* $builder->hydrator(new Setter()); |
|
13
|
|
|
* |
|
14
|
|
|
* // The property name is "myProp" |
|
15
|
|
|
* $builder->hydrator(new Setter('myProp')); |
|
16
|
|
|
* |
|
17
|
|
|
* // Apply a transformation to the value |
|
18
|
|
|
* $builder->hydrator(new Setter(function ($value, ChildInterface $input) { |
|
19
|
|
|
* return doTransform($value); |
|
20
|
|
|
* })); |
|
21
|
|
|
* |
|
22
|
|
|
* // Define property name and transformer |
|
23
|
|
|
* $builder->hydrator(new Setter('myProp', function ($value, ChildInterface $input) { |
|
24
|
|
|
* return doTransform($value); |
|
25
|
|
|
* })); |
|
26
|
|
|
* |
|
27
|
|
|
* // Use a custom accessor. $mode is equals to HydratorInterface::HYDRATION |
|
28
|
|
|
* $builder->hydrator(new Setter(null, null, function ($entity, $value, $mode, Setter $setter) { |
|
29
|
|
|
* return $entity->myCustomSetter($value); |
|
30
|
|
|
* })); |
|
31
|
|
|
* </code> |
|
32
|
|
|
* |
|
33
|
|
|
* @see ChildBuilder::setter() |
|
34
|
|
|
*/ |
|
35
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY)] |
|
36
|
|
|
final class Setter extends AbstractAccessor implements HydratorInterface |
|
37
|
|
|
{ |
|
38
|
|
|
/** |
|
39
|
|
|
* {@inheritdoc} |
|
40
|
|
|
*/ |
|
41
|
53 |
|
public function hydrate(&$target, $value): void |
|
42
|
|
|
{ |
|
43
|
53 |
|
if ($this->transformer) { |
|
44
|
11 |
|
$value = ($this->transformer)($value, $this->input); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
53 |
|
if ($this->customAccessor !== null) { |
|
48
|
1 |
|
($this->customAccessor)($target, $value, self::HYDRATION, $this); |
|
49
|
|
|
} else { |
|
50
|
52 |
|
$this->propertyAccessor->setValue($target, $this->prepareAccessorPath($target), $value); |
|
51
|
|
|
} |
|
52
|
53 |
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|