-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathSimpleDTO.php
562 lines (464 loc) · 15.9 KB
/
SimpleDTO.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
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
<?php
declare(strict_types=1);
namespace WendellAdriel\ValidatedDTO;
use BackedEnum;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
use JsonSerializable;
use ReflectionClass;
use ReflectionProperty;
use UnitEnum;
use WendellAdriel\ValidatedDTO\Attributes\Cast;
use WendellAdriel\ValidatedDTO\Attributes\DefaultValue;
use WendellAdriel\ValidatedDTO\Attributes\Map;
use WendellAdriel\ValidatedDTO\Attributes\Rules;
use WendellAdriel\ValidatedDTO\Casting\ArrayCast;
use WendellAdriel\ValidatedDTO\Casting\Castable;
use WendellAdriel\ValidatedDTO\Casting\EnumCast;
use WendellAdriel\ValidatedDTO\Concerns\DataResolver;
use WendellAdriel\ValidatedDTO\Concerns\DataTransformer;
use WendellAdriel\ValidatedDTO\Contracts\BaseDTO;
use WendellAdriel\ValidatedDTO\Exceptions\CastTargetException;
use WendellAdriel\ValidatedDTO\Exceptions\MissingCastTypeException;
abstract class SimpleDTO implements BaseDTO, CastsAttributes, JsonSerializable
{
use DataResolver, DataTransformer;
public bool $lazyValidation = false;
/** @internal */
protected array $dtoData = [];
/** @internal */
protected array $validatedData = [];
/** @internal */
protected bool $requireCasting = false;
/** @internal */
protected \Illuminate\Contracts\Validation\Validator|\Illuminate\Validation\Validator $validator;
/** @internal */
protected array $dtoRules = [];
/** @internal */
protected array $dtoMessages = [];
/** @internal */
protected array $dtoDefaults = [];
/** @internal */
protected array $dtoCasts = [];
/** @internal */
protected array $dtoMapData = [];
/** @internal */
protected array $dtoMapTransform = [];
/**
* @throws ValidationException|MissingCastTypeException|CastTargetException
*/
public function __construct(?array $data = null)
{
if (is_null($data)) {
return;
}
$this->buildAttributesData();
$this->dtoData = $this->buildDataForValidation($data);
$this->initConfig();
$this->isValidData()
? $this->passedValidation()
: $this->failedValidation();
}
public function __set(string $name, mixed $value): void
{
$this->{$name} = $value;
}
public function __get(string $name): mixed
{
return $this->{$name} ?? null;
}
/**
* Defines the default values for the properties of the DTO.
*/
abstract protected function defaults(): array;
/**
* Defines the type casting for the properties of the DTO.
*/
abstract protected function casts(): array;
/**
* Cast the given value to a DTO instance.
*
* @param Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return $this
*
* @throws ValidationException|MissingCastTypeException|CastTargetException
*/
public function get($model, $key, $value, $attributes)
{
$arrayCast = new ArrayCast();
return new static($arrayCast->cast($key, $value));
}
/**
* Prepare the value for storage.
*
* @param Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return string
*/
public function set($model, $key, $value, $attributes)
{
if (is_string($value)) {
return $value;
}
if (is_array($value)) {
return json_encode($value);
}
if ($value instanceof ValidatedDTO) {
return $value->toJson();
}
return '';
}
/*
* JsonSerializable
*/
public function jsonSerialize(): mixed
{
return $this->toArray();
}
/**
* Maps the DTO properties before the DTO instantiation.
*/
protected function mapData(): array
{
return [];
}
/**
* Maps the DTO properties before the DTO transformation.
*/
protected function mapToTransform(): array
{
return [];
}
/**
* @throws MissingCastTypeException|CastTargetException
*/
protected function passedValidation(bool $forceCast = false): void
{
$this->validatedData = $this->validatedData($forceCast);
/** @var array<Castable> $casts */
$casts = $this->buildCasts();
foreach ($this->validatedData as $key => $value) {
$this->{$key} = $value;
}
$defaults = [
...$this->defaults(),
...$this->dtoDefaults,
];
foreach ($defaults as $key => $value) {
if (
! property_exists($this, $key) ||
! isset($this->{$key})
) {
if (! array_key_exists($key, $casts)) {
if ($this->requireCasting) {
throw new MissingCastTypeException($key);
}
$this->{$key} = $value;
$this->validatedData[$key] = $value;
continue;
}
$formatted = $this->shouldReturnNull($key, $value)
? null
: $this->castValue($casts[$key], $key, $value, $forceCast);
$this->{$key} = $formatted;
$this->validatedData[$key] = $formatted;
}
}
$this->dtoData = [];
}
protected function failedValidation(): void
{
// Do nothing
}
protected function isValidData(): bool
{
return true;
}
/**
* Builds the validated data from the given data and the rules.
*
* @throws MissingCastTypeException|CastTargetException
*/
protected function validatedData(bool $forceCast = false): array
{
$acceptedKeys = $this->getAcceptedProperties();
$result = [];
/** @var array<Castable> $casts */
$casts = $this->buildCasts();
foreach ($this->dtoData as $key => $value) {
if (in_array($key, $acceptedKeys)) {
if (! array_key_exists($key, $casts)) {
if ($this->requireCasting) {
throw new MissingCastTypeException($key);
}
$result[$key] = $value;
continue;
}
$result[$key] = $this->shouldReturnNull($key, $value)
? null
: $this->castValue($casts[$key], $key, $value, $forceCast);
}
}
foreach ($acceptedKeys as $property) {
if (! array_key_exists($property, $result)) {
$this->{$property} = null;
}
}
return $result;
}
/**
* @throws CastTargetException
*/
protected function castValue(mixed $cast, string $key, mixed $value, bool $forceCast = false): mixed
{
if ($this->lazyValidation && ! $forceCast) {
return $value;
}
if ($cast instanceof Castable) {
return $cast->cast($key, $value);
}
if (! is_callable($cast)) {
throw new CastTargetException($key);
}
return $cast($key, $value);
}
protected function shouldReturnNull(string $key, mixed $value): bool
{
return is_null($value);
}
protected function buildCasts(): array
{
$casts = [];
foreach ($this->dtoCasts as $property => $cast) {
if (is_null($cast->param)) {
$casts[$property] = new $cast->type();
continue;
}
$param = $cast->type === EnumCast::class
? $cast->param
: new $cast->param();
$casts[$property] = new $cast->type($param);
}
return [
...$this->casts(),
...$casts,
];
}
protected function buildDataForExport(): array
{
$mapping = [
...$this->mapToTransform(),
...$this->dtoMapTransform,
];
$data = $this->validatedData;
foreach ($this->getAcceptedProperties() as $property) {
if (! array_key_exists($property, $data) && isset($this->{$property})) {
$data[$property] = $this->{$property};
}
}
return $this->mapDTOData($mapping, $data);
}
protected function buildDataForValidation(array $data): array
{
$mapping = [
...$this->mapData(),
...$this->dtoMapData,
];
return $this->mapDTOData($mapping, $data);
}
private function buildAttributesData(): void
{
$publicProperties = $this->getPublicProperties();
$validatedProperties = $this->getPropertiesForAttribute($publicProperties, Rules::class);
foreach ($validatedProperties as $property => $attribute) {
$attributeInstance = $attribute->newInstance();
$this->dtoRules[$property] = $attributeInstance->rules;
$this->dtoMessages[$property] = $attributeInstance->messages ?? [];
}
$this->dtoMessages = array_filter(
$this->dtoMessages,
fn ($value) => $value !== []
);
$defaultProperties = $this->getPropertiesForAttribute($publicProperties, DefaultValue::class);
foreach ($defaultProperties as $property => $attribute) {
$attributeInstance = $attribute->newInstance();
$this->dtoDefaults[$property] = $attributeInstance->value;
}
$castProperties = $this->getPropertiesForAttribute($publicProperties, Cast::class);
foreach ($castProperties as $property => $attribute) {
$attributeInstance = $attribute->newInstance();
$this->dtoCasts[$property] = $attributeInstance;
}
$mapDataProperties = $this->getPropertiesForAttribute($publicProperties, Map::class);
foreach ($mapDataProperties as $property => $attribute) {
$attributeInstance = $attribute->newInstance();
if (! blank($attributeInstance->data)) {
$this->dtoMapData[$attributeInstance->data] = $property;
}
if (! blank($attributeInstance->transform)) {
$this->dtoMapTransform[$property] = $attributeInstance->transform;
}
}
}
private function getPublicProperties(): array
{
$reflectionClass = new ReflectionClass($this);
$dtoProperties = [];
foreach ($reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
if ($this->isforbiddenProperty($property->getName())) {
continue;
}
$reflectionProperty = new ReflectionProperty($this, $property->getName());
$attributes = $reflectionProperty->getAttributes();
$dtoProperties[$property->getName()] = $attributes;
}
return $dtoProperties;
}
private function getPropertiesForAttribute(array $properties, string $attribute): array
{
$result = [];
foreach ($properties as $property => $attributes) {
foreach ($attributes as $attr) {
if ($attr->getName() === $attribute) {
$result[$property] = $attr;
}
}
}
return $result;
}
private function mapDTOData(array $mapping, array $data): array
{
$mappedData = [];
foreach ($data as $key => $value) {
$properties = $this->getMappedProperties($mapping, $key);
if ($properties !== [] && $this->isArrayable($value)) {
$formatted = $this->formatArrayableValue($value);
foreach ($properties as $property => $mappedValue) {
$mappedData[$mappedValue] = $formatted[$property] ?? null;
}
continue;
}
$property = array_key_exists($key, $mapping)
? $mapping[$key]
: $key;
if (isset($this->{$key}) && $value !== $this->{$key}) {
$value = $this->{$key};
}
$mappedData[$property] = $this->isArrayable($value)
? $this->formatArrayableValue($value)
: $value;
}
return $mappedData;
}
private function getMappedProperties(array $mapping, string $key): array
{
$properties = [];
foreach ($mapping as $mappedKey => $mappedValue) {
if (str_starts_with($mappedKey, "{$key}.")) {
$arrayKey = str_replace("{$key}.", '', $mappedKey);
$properties[$arrayKey] = $mappedValue;
}
if (str_starts_with($mappedValue, "{$key}.")) {
$arrayKey = str_replace("{$key}.", '', $mappedValue);
$properties[$arrayKey] = $mappedKey;
}
}
return $properties;
}
private function isArrayable(mixed $value): bool
{
return is_array($value) ||
$value instanceof Arrayable ||
$value instanceof Collection ||
$value instanceof ValidatedDTO ||
$value instanceof Model ||
(is_object($value) && ! ($value instanceof UploadedFile));
}
private function formatArrayableValue(mixed $value): array|int|string
{
return match (true) {
is_array($value) => $value,
$value instanceof BackedEnum => $value->value,
$value instanceof UnitEnum => $value->name,
$value instanceof Carbon || $value instanceof CarbonImmutable => $value->toISOString(true),
$value instanceof Collection => $this->transformCollectionToArray($value),
$value instanceof Model => $this->transformModelToArray($value),
$value instanceof SimpleDTO => $this->transformDTOToArray($value),
$value instanceof Arrayable => $value->toArray(),
is_object($value) => (array) $value,
default => [],
};
}
private function transformCollectionToArray(Collection $collection): array
{
return $collection->map(function ($item) {
return $this->isArrayable($item)
? $this->formatArrayableValue($item)
: $item;
})->toArray();
}
private function transformModelToArray(Model $model): array
{
$result = [];
foreach ($model->getAttributes() as $key => $value) {
$result[$key] = $this->isArrayable($value)
? $this->formatArrayableValue($value)
: $value;
}
return $result;
}
private function transformDTOToArray(SimpleDTO $dto): array
{
$result = [];
foreach ($dto->validatedData as $key => $value) {
$result[$key] = $this->isArrayable($value)
? $this->formatArrayableValue($value)
: $value;
}
return $result;
}
private function initConfig(): void
{
$config = config('dto');
if (! empty($config) && array_key_exists('require_casting', $config)) {
$this->requireCasting = $config['require_casting'];
}
}
private function getAcceptedProperties(): array
{
$acceptedKeys = [];
foreach (get_class_vars($this::class) as $key => $value) {
if (! $this->isforbiddenProperty($key)) {
$acceptedKeys[] = $key;
}
}
return $acceptedKeys;
}
private function isforbiddenProperty(string $property): bool
{
return in_array($property, [
'dtoData',
'validatedData',
'requireCasting',
'validator',
'dtoRules',
'dtoMessages',
'dtoDefaults',
'dtoCasts',
'dtoMapData',
'dtoMapTransform',
'lazyValidation',
]);
}
}