-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValueGenerator.php
More file actions
95 lines (82 loc) · 2.72 KB
/
Copy pathValueGenerator.php
File metadata and controls
95 lines (82 loc) · 2.72 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
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace Bdf\Form\Aggregate\Value;
use Bdf\Form\ElementInterface;
use Override;
use ReflectionClass;
use function class_exists;
use function is_callable;
use function is_object;
use function is_string;
/**
* 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 as array|object
* @implements ValueGeneratorInterface<T>
*
* @psalm-suppress InvalidDocblock
*/
final class ValueGenerator implements ValueGeneratorInterface
{
/**
* @var ValueGeneratorInterface<T>
*/
private ValueGeneratorInterface $generator;
/**
* ValueGenerator constructor.
*
* @param callable(ElementInterface):T|T|class-string $value
*/
public function __construct(mixed $value = [])
{
$this->generator = self::fromValue($value, true);
}
#[Override]
public function attach(mixed $entity): void
{
$this->generator = self::fromValue($entity, false);
}
#[Override]
public function generate(ElementInterface $element): array|object
{
return $this->generator->generate($element);
}
#[Override]
public function finalize(object|array $value): object|array
{
return $this->generator->finalize($value);
}
/**
* @param callable(ElementInterface):U|U|class-string $value
* @return ValueGeneratorInterface<U>
* @template U as array|object
*
* @psalm-suppress InvalidReturnStatement
* @psalm-suppress InvalidReturnType
*/
private static function fromValue(mixed $value, bool $cloneObjectValue): ValueGeneratorInterface
{
if (is_string($value) && class_exists($value)) {
$calUseDefaultConstructor = (new ReflectionClass($value)->getConstructor()?->getNumberOfRequiredParameters() ?? 0) === 0;
return $calUseDefaultConstructor
? new DefaultConstructorValueGenerator($value)
: new ConstructorValueGenerator($value)
;
}
if (is_callable($value)) {
/** @psalm-suppress PossiblyInvalidFunctionCall */
return new ClosureValueGenerator($value(...));
}
if (is_object($value) && $cloneObjectValue) {
return new ObjectValueGenerator($value);
}
/** @psalm-suppress PossiblyInvalidArgument */
return new SimpleValueGenerator($value);
}
}