-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValueGenerator.php
75 lines (64 loc) · 1.75 KB
/
ValueGenerator.php
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
<?php
namespace Bdf\Form\Aggregate\Value;
use Bdf\Form\ElementInterface;
/**
* The base value generator implementation
*
* <code>
* (new ValueGenerator())->generate($form); // Will generate an empty array
* (new ValueGenerator(MyEntity::class))->generate($form); // Will call the default constructor of MyEntity
* (new ValueGenerator($entity))->generate($form); // Will clone the instance of $entity
* (new ValueGenerator(function (FormInterface $form) { return new MyEntity(...); }))->generate($form); // Custom generator
* </code>
*
* @template T
* @implements ValueGeneratorInterface<T>
*/
final class ValueGenerator implements ValueGeneratorInterface
{
/**
* @var callable():T|T|class-string<T>
*/
private $value;
/**
* @var callable():T|T|class-string<T>|null
*/
private $attachment;
/**
* ValueGenerator constructor.
*
* @param callable():T|T|class-string<T> $value
*/
public function __construct($value = [])
{
/** @psalm-suppress PropertyTypeCoercion */
$this->value = $value;
}
/**
* {@inheritdoc}
*/
public function attach($entity): void
{
/** @psalm-suppress PropertyTypeCoercion */
$this->attachment = $entity;
}
/**
* {@inheritdoc}
*/
public function generate(ElementInterface $element)
{
$value = $this->attachment ?? $this->value;
if (is_string($value)) {
/** @var T */
return new $value;
}
if (is_callable($value)) {
return ($value)($element);
}
// Only clone value if it's not attached
if (!$this->attachment && is_object($value)) {
return clone $value;
}
return $value;
}
}