-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathInstantiator.php
More file actions
234 lines (190 loc) · 6.56 KB
/
Instantiator.php
File metadata and controls
234 lines (190 loc) · 6.56 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
<?php
/*
* This file is part of the zenstruck/foundry package.
*
* (c) Kevin Bond <kevinbond@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Zenstruck\Foundry\Object;
use Zenstruck\Foundry\Factory;
use Zenstruck\Foundry\ForceValue;
/**
* @author Kevin Bond <kevinbond@gmail.com>
*
* @phpstan-import-type Parameters from Factory
*/
final class Instantiator
{
private const WITH_CONSTRUCTOR = '_with_constructor';
private const WITHOUT_CONSTRUCTOR = '_without_constructor';
private Hydrator $hydrator;
private bool $hydration = true;
private function __construct(private string|\Closure $mode) // @phpstan-ignore missingType.callable
{
$this->hydrator = new Hydrator();
}
/**
* @template T of object
*
* @param class-string<T> $class
* @phpstan-param Parameters $parameters
*
* @return T
*/
public function __invoke(array $parameters, string $class): object
{
$object = $this->instantiate($parameters, $class);
return $this->hydration ? ($this->hydrator)($object, $parameters) : $object;
}
public static function withConstructor(): self
{
return new self(self::WITH_CONSTRUCTOR);
}
public static function withoutConstructor(): self
{
return new self(self::WITHOUT_CONSTRUCTOR);
}
public static function namedConstructor(string $method): self
{
return new self($method);
}
public static function use(callable $factory): self // @phpstan-ignore missingType.callable
{
return new self($factory(...));
}
/**
* Ignore attributes that can't be set to object.
*
* @param string ...$parameters The parameters you'd like the hydrator to ignore (if empty, ignore any extra)
*/
public function allowExtra(string ...$parameters): self
{
$clone = clone $this;
$clone->hydrator = $clone->hydrator->allowExtra(...$parameters);
$clone->hydration = true;
return $clone;
}
/**
* Always force properties, never use setters (still uses constructor unless disabled).
*
* @param string ...$properties The properties you'd like the hydrator to "force set" (if empty, force set all)
*/
public function alwaysForce(string ...$properties): self
{
$clone = clone $this;
$clone->hydrator = $clone->hydrator->alwaysForce(...$properties);
$clone->hydration = true;
return $clone;
}
public function enableHydration(): self
{
$clone = clone $this;
$clone->hydration = true;
return $clone;
}
public function disableHydration(): self
{
$clone = clone $this;
$clone->hydration = false;
return $clone;
}
/**
* @internal
*/
public function hydrator(): Hydrator
{
return $this->hydrator;
}
/**
* @template T of object
*
* @param class-string<T> $class
* @phpstan-param Parameters $parameters
*
* @return T
*/
private function instantiate(array &$parameters, string $class): object
{
$refClass = new \ReflectionClass($class);
if (self::WITHOUT_CONSTRUCTOR === $this->mode) {
return $refClass->newInstanceWithoutConstructor();
}
if (!$factory = $this->factoryFor($refClass)) {
return $refClass->newInstance();
}
$arguments = [];
/** @var \ReflectionParameter $parameter */
foreach ($factory->getParameters() as $parameter) {
if (\array_key_exists($parameter->name, $parameters)) {
if ($parameter->isVariadic()) {
$arguments = \array_merge($arguments, $parameters[$parameter->name]);
} else {
$arguments[] = $parameters[$parameter->name];
}
unset($parameters[$parameter->name]);
continue;
}
if ($parameter->isDefaultValueAvailable()) {
$arguments[] = $parameter->getDefaultValue();
continue;
}
throw new \LogicException(\sprintf('Missing required argument "%s" for "%s::%s()".', $parameter->name, $class, $factory->name));
}
if ($factory instanceof \ReflectionMethod && $factory->isConstructor()) {
return $refClass->newInstance(
...ForceValue::unwrap($arguments)
);
}
$object = $factory instanceof \ReflectionMethod ? $factory->invoke(null, ...ForceValue::unwrap($arguments)) : $factory->invoke(...ForceValue::unwrap($arguments));
if (!$object instanceof $class) {
throw new \LogicException(\sprintf('Named constructor "%s" for "%s" must return an instance of "%s".', $factory->name, $class, $class));
}
return $object;
}
/**
* @param \ReflectionClass<object> $class
*/
private function factoryFor(\ReflectionClass $class): \ReflectionFunction|\ReflectionMethod|null
{
if ($this->mode instanceof \Closure) {
return new \ReflectionFunction(($this->mode)(...));
}
if (self::WITH_CONSTRUCTOR === $this->mode) {
return self::constructorFor($class);
}
return self::namedConstructorFor($class, $this->mode);
}
/**
* @param \ReflectionClass<object> $class
*/
private static function namedConstructorFor(\ReflectionClass $class, string $name): \ReflectionMethod
{
try {
$method = $class->getMethod($name);
} catch (\ReflectionException) {
throw new \LogicException(\sprintf('Named constructor "%s" for "%s" does not exist.', $name, $class->getName()));
}
if (!$method->isPublic()) {
throw new \LogicException(\sprintf('Named constructor "%s" for "%s" is not public.', $name, $class->getName()));
}
if (!$method->isStatic()) {
throw new \LogicException(\sprintf('Named constructor "%s" for "%s" is not static.', $name, $class->getName()));
}
return $method;
}
/**
* @param \ReflectionClass<object> $class
*/
private static function constructorFor(\ReflectionClass $class): ?\ReflectionMethod
{
if (!$constructor = $class->getConstructor()) {
return null;
}
if (!$constructor->isPublic()) {
throw new \LogicException(\sprintf('Constructor for "%s" is not public.', $class->getName()));
}
return $constructor;
}
}