-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseData.php
More file actions
414 lines (338 loc) · 13.7 KB
/
Copy pathBaseData.php
File metadata and controls
414 lines (338 loc) · 13.7 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<?php
declare(strict_types=1);
namespace StdOut\SimpleDataObjects;
use Illuminate\Container\Container;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\LazyCollection;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Factory as ValidatorFactory;
use Illuminate\Validation\ValidationException;
use JsonSerializable;
use StdOut\SimpleDataObjects\Contracts\DataObject;
use StdOut\SimpleDataObjects\Exceptions\DataHydrationException;
use StdOut\SimpleDataObjects\Support\ClassMeta;
use StdOut\SimpleDataObjects\Support\HydratorCompiler;
use StdOut\SimpleDataObjects\Support\InputNormalizer;
use StdOut\SimpleDataObjects\Support\MetadataRegistry;
use StdOut\SimpleDataObjects\Support\SerializerCompiler;
use StdOut\SimpleDataObjects\Support\ValueCaster;
use Stringable;
abstract class BaseData implements Arrayable, DataObject, JsonSerializable, Stringable
{
private static ?ValidatorFactory $validatorFactory = null;
/** @var array<class-string, \ReflectionClass<BaseData>> */
private static array $reflectors = [];
/**
* Universal factory: accepts an array, an Eloquent model or any
* Arrayable, stdClass, JsonSerializable, any Traversable, a JSON string,
* a plain object (public properties), or an existing instance of the
* same class (returned as-is — instances are immutable).
*/
public static function from(mixed $data): static
{
$hydrate = HydratorCompiler::$hydrators[static::class] ?? HydratorCompiler::compile(static::class);
if (is_array($data)) {
/** @var static */
return $hydrate($data);
}
if ($data instanceof static) {
return $data;
}
/** @var static */
return $hydrate(InputNormalizer::normalize(static::class, $data));
}
/**
* Returns an uninitialized lazy ghost (PHP 8.4): hydration cost is
* deferred until the first property access. Use when many DTOs are
* created but only some are ever read. Note that invalid input therefore
* throws on first access, not here.
*/
public static function fromLazy(mixed $data): static
{
$class = static::class;
$reflector = self::$reflectors[$class] ??= new \ReflectionClass($class);
// A ghost's class is fixed at creation, so a #[Discriminator] class
// must resolve the concrete class eagerly; hydration stays deferred.
if ($reflector->isAbstract()) {
$meta = MetadataRegistry::get($class);
if ($meta->discriminatorField !== null) {
$normalized = is_array($data) ? $data : InputNormalizer::normalize($class, $data);
return self::resolveDiscriminated($meta, $normalized)::fromLazy($normalized);
}
}
/** @var static */
return $reflector->newLazyGhost(static function (object $ghost) use ($class, $data): void {
$normalized = is_array($data) ? $data : InputNormalizer::normalize($class, $data);
// Kept inside the initializer (not hoisted into fromLazy()) so a
// cold metadata cache is only ever built on first property access.
$meta = MetadataRegistry::get($class);
if (! $meta->hasConstructor) {
(HydratorCompiler::$populators[$class] ?? HydratorCompiler::compilePopulate($class))($normalized, $ghost);
return;
}
$args = (HydratorCompiler::$argResolvers[$class] ?? HydratorCompiler::compileArgs($class))($normalized);
$ghost->__construct(...$args);
// Hybrid: the constructor only covers its own parameters — the
// extra properties still need populating, same mechanism as the
// constructor-less path above.
if ($meta->hasExtraProperties) {
(HydratorCompiler::$populators[$class] ?? HydratorCompiler::compilePopulate($class))($normalized, $ghost);
}
});
}
public static function tryFrom(mixed $data): ?static
{
try {
return static::from($data);
} catch (\Throwable) {
return null;
}
}
/**
* Like from(), but never throws — every failure is collected into the
* returned result instead of aborting on the first one.
*
* @return HydrationResult<static>
*/
public static function fromResult(mixed $data): HydrationResult
{
$collect = HydratorCompiler::$collectingHydrators[static::class] ?? HydratorCompiler::compileCollecting(static::class);
if (is_array($data)) {
/** @var HydrationResult<static> */
return $collect($data);
}
if ($data instanceof static) {
return HydrationResult::success($data);
}
try {
$data = InputNormalizer::normalize(static::class, $data);
} catch (DataHydrationException $e) {
return HydrationResult::failure(['$input' => $e->getMessage()]);
}
/** @var HydrationResult<static> */
return $collect($data);
}
/**
* @return TypedDataCollection<static>
*/
public static function collection(iterable $items): TypedDataCollection
{
return TypedDataCollection::of(static::class, $items);
}
/**
* Like `collection()`, but hydrates one item at a time as the collection
* is consumed instead of materializing the whole array upfront. Use this
* for large iterables (a DB cursor, a generator reading a big CSV) where
* holding every hydrated instance in memory at once would be wasteful.
*
* @return LazyCollection<int, static>
*/
public static function lazyCollection(iterable $items): LazyCollection
{
$class = static::class;
return LazyCollection::make(static function () use ($items, $class): \Generator {
$hydrate = HydratorCompiler::$hydrators[$class] ?? HydratorCompiler::compile($class);
foreach ($items as $item) {
yield $item instanceof $class
? $item
: $hydrate(is_array($item) ? $item : InputNormalizer::normalize($class, $item));
}
});
}
/** Explicit alias of from() for JSON input — same decoding and errors. */
public static function fromJson(string $json): static
{
return static::from($json);
}
public function with(mixed ...$overrides): static
{
$meta = MetadataRegistry::get(static::class);
$current = get_object_vars($this);
$ctorArgs = [];
$extra = [];
foreach ($meta->parameters as $param) {
if (array_key_exists($param->phpName, $overrides)) {
$value = $overrides[$param->phpName];
$value = $param->isPlain ? $value : ValueCaster::cast($param, $value);
unset($overrides[$param->phpName]);
} else {
$value = $current[$param->phpName];
}
if ($param->viaConstructor) {
$ctorArgs[] = $value;
} else {
$extra[$param->phpName] = $value;
}
}
if ($overrides !== []) {
throw new \InvalidArgumentException(
sprintf('Unknown propert%s [%s] for %s::with().', count($overrides) === 1 ? 'y' : 'ies', implode(', ', array_keys($overrides)), static::class),
);
}
$instance = $meta->hasConstructor ? new static(...$ctorArgs) : new static;
// Extra (non-constructor) properties — constructor-less classes and
// hybrid classes' extra fields. Legal even for readonly properties:
// the write happens from BaseData's own scope, an ancestor of every
// subclass, which PHP treats as within the declaring scope.
foreach ($extra as $phpName => $value) {
$instance->{$phpName} = $value;
}
return $instance;
}
public static function fromValidated(mixed $data): static
{
$array = is_array($data) ? $data : InputNormalizer::normalize(static::class, $data);
$meta = MetadataRegistry::get(static::class);
// Delegate before validating so the concrete class's rules apply,
// not the (usually empty) rules of the abstract base.
if ($meta->discriminatorField !== null) {
/** @var static */
return self::resolveDiscriminated($meta, $array)::fromValidated($array);
}
if ($meta->validationRules !== []) {
static::validatorFactory()->make($array, $meta->validationRules)->validate();
}
return static::from($array);
}
/**
* fromResult(), with Rules validation errors merged into the same map
* (validation errors win on a key collision). Never throws.
*
* @return HydrationResult<static>
*/
public static function fromValidatedResult(mixed $data): HydrationResult
{
if (! is_array($data)) {
try {
$data = InputNormalizer::normalize(static::class, $data);
} catch (DataHydrationException $e) {
return HydrationResult::failure(['$input' => $e->getMessage()]);
}
}
$meta = MetadataRegistry::get(static::class);
// Same delegation as fromValidated(): the concrete class's rules apply
if ($meta->discriminatorField !== null) {
try {
$target = self::resolveDiscriminated($meta, $data);
} catch (DataHydrationException $e) {
return HydrationResult::failure([(string) $meta->discriminatorField => $e->getMessage()]);
}
/** @var HydrationResult<static> */
return $target::fromValidatedResult($data);
}
$result = static::fromResult($data);
if ($meta->validationRules === []) {
return $result;
}
$validator = static::validatorFactory()->make($data, $meta->validationRules);
if (! $validator->fails()) {
return $result;
}
$validationErrors = [];
foreach ($validator->errors()->messages() as $key => $messages) {
$validationErrors[$key] = $messages[0];
}
return HydrationResult::failure([...$result->errors(), ...$validationErrors]);
}
/** @throws ValidationException */
public static function validate(mixed $data): void
{
$meta = MetadataRegistry::get(static::class);
// Same delegation as fromValidated(): the concrete class's rules apply
if ($meta->discriminatorField !== null) {
$array = is_array($data) ? $data : InputNormalizer::normalize(static::class, $data);
self::resolveDiscriminated($meta, $array)::validate($array);
return;
}
if ($meta->validationRules === []) {
return;
}
$array = is_array($data) ? $data : InputNormalizer::normalize(static::class, $data);
static::validatorFactory()
->make($array, $meta->validationRules)
->validate();
}
/**
* @return class-string<static>
*
* @throws DataHydrationException
*/
private static function resolveDiscriminated(ClassMeta $meta, array $data): string
{
/** @var class-string<static>|null $target */
$target = $meta->resolveDiscriminatedClass($data);
return $target ?? throw DataHydrationException::unresolvedDiscriminator(
static::class,
(string) $meta->discriminatorField,
$data[$meta->discriminatorField] ?? null,
);
}
public static function setValidatorFactory(ValidatorFactory $factory): void
{
self::$validatorFactory = $factory;
}
private static function validatorFactory(): ValidatorFactory
{
if (self::$validatorFactory !== null) {
return self::$validatorFactory;
}
$container = Container::getInstance();
if ($container->bound('validator')) {
// Not memoized: long-running runtimes (Octane) may rebind the
// container between requests; resolving a singleton is cheap.
/** @var ValidatorFactory $factory */
$factory = $container->make('validator');
return $factory;
}
return self::$validatorFactory = new ValidatorFactory(
new Translator(
new ArrayLoader,
'en',
),
);
}
public function equals(self $other): bool
{
return $other::class === static::class && $this->toArray() === $other->toArray();
}
/** @return array<string, array{0: mixed, 1: mixed}> */
public function diff(self $other): array
{
$a = $this->toArray();
$b = $other->toArray();
$result = [];
foreach (array_keys($a + $b) as $key) {
$aVal = $a[$key] ?? null;
$bVal = $b[$key] ?? null;
if ($aVal !== $bVal) {
$result[$key] = [$aVal, $bVal];
}
}
return $result;
}
public function toArray(): array
{
return (SerializerCompiler::$serializers[static::class] ?? SerializerCompiler::compile(static::class))($this);
}
public function toJson(int $flags = 0): string
{
return json_encode($this->toArray(), $flags | JSON_THROW_ON_ERROR);
}
public function only(string ...$keys): array
{
return array_intersect_key($this->toArray(), array_flip($keys));
}
public function except(string ...$keys): array
{
return array_diff_key($this->toArray(), array_flip($keys));
}
public function jsonSerialize(): array
{
return $this->toArray();
}
public function __toString(): string
{
return $this->toJson();
}
}