This repository was archived by the owner on Jul 31, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializable.php
More file actions
329 lines (282 loc) · 12.1 KB
/
Copy pathSerializable.php
File metadata and controls
329 lines (282 loc) · 12.1 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
<?php
namespace Flolefebvre\Serializer;
use Carbon\Carbon;
use ErrorException;
use ReflectionClass;
use ReflectionProperty;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionUnionType;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use ReflectionIntersectionType;
use Illuminate\Http\JsonResponse;
use Flolefebvre\Serializer\Rules\Rule;
use Illuminate\Support\Facades\Validator;
use Flolefebvre\Serializer\Casts\TypeCast;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Responsable;
use Symfony\Component\HttpFoundation\Response;
use Flolefebvre\Serializer\Casts\CarbonStringCast;
use Flolefebvre\Serializer\Rules\TypeExtendsClass;
use Flolefebvre\Serializer\Exceptions\MissingPropertyException;
use Flolefebvre\Serializer\Exceptions\TypesDoNotMatchException;
use Flolefebvre\Serializer\Exceptions\UnionTypeCannotBeUnserializedException;
use Flolefebvre\Serializer\Exceptions\IntersectionTypeCannotBeUnserializedException;
abstract class Serializable implements Arrayable, Responsable
{
private static array $defaultCasts = [
Carbon::class => CarbonStringCast::class
];
public function toArray(): array
{
$class = new ReflectionClass($this);
$properties = $class->getProperties(ReflectionProperty::IS_PUBLIC);
$array = [
'_type' => static::class
];
foreach ($properties as $property) {
$propertyName = $property->getName();
$propertyValue = $this->$propertyName;
$typeCast = static::getTypeCast($property);;
if ($typeCast !== null) {
$array[$propertyName] = $typeCast->serialize($propertyValue);
continue;
}
if (is_iterable($propertyValue)) {
$subVars = [];
foreach ($propertyValue as $key => &$v) {
if ($v instanceof Serializable)
$subVars[$key] = $v->toArray();
else
$subVars[$key] = $v;
}
$array[$propertyName] = $subVars;
} elseif (is_object($propertyValue)) {
$array[$propertyName] = $propertyValue->toArray();
} else {
$array[$propertyName] = $propertyValue;
}
}
// Makes sure the return value always has the same order
// event if the user moves properties around
ksort($array);
return $array;
}
private static function getTypeCast(ReflectionParameter|ReflectionProperty $param): ?TypeCast
{
$castAttributes = $param->getAttributes(CastTypeWith::class);
if (count($castAttributes) > 0) {
$castAttribute = $castAttributes[0]->newInstance();
return app($castAttribute->class);
}
$typeName = $param->getType()?->getName();
if (isset(static::$defaultCasts[$typeName])) {
return app(static::$defaultCasts[$typeName]);
}
return null;
}
private static function makeValidator(array $array, string $prefix = ''): array
{
$type = $array['_type'] ?? static::class;
$validator = [
$prefix . '_type' => [new TypeExtendsClass(static::class)]
];
$constructor = new ReflectionClass($type)->getConstructor();
if ($constructor === null) return $validator;
foreach ($constructor->getParameters() as $param) {
$paramName = $param->getName();
$paramType = $param->getType();
if ($paramType instanceof ReflectionNamedType) {
$paramTypeName = $paramType->getName();
$rules = [];
if ($paramType->allowsNull() || $param->isDefaultValueAvailable()) {
$rules[] = 'nullable';
} else {
if ($paramTypeName === 'array') {
$rules[] = 'present';
} else {
$rules[] = 'required';
}
}
$ruleAttributes = $param->getAttributes(Rule::class);
$rulesFromAttributes = array_merge(...array_map(fn($r) => $r->newInstance()->toArray(), $ruleAttributes));
$rules = [...$rules, ...$rulesFromAttributes];
$typeCast = static::getTypeCast($param);;
if ($typeCast !== null) {
$rules[] = $typeCast->serializedType;
$validator[$prefix . $paramName] = $rules;
continue;
}
if (class_exists($paramTypeName) && isset($array[$paramName])) {
$value = $array[$paramName];
$validator = [...$validator, ...$paramTypeName::makeValidator($value, $prefix . $paramName . '.')];
} else {
$rules[] = $paramType->getName();
}
$validator[$prefix . $paramName] = $rules;
if ($paramType->getName() === 'array') {
$attributes = $param->getAttributes(ArrayType::class);
$arrayType = count($attributes) === 0
? Serializable::class
: $attributes[0]->newInstance()->type;
if ($arrayType == 'mixed') continue;
elseif (class_exists($arrayType)) {
$value = $array[$paramName] ?? null;
$subValidators = [];
if (is_array($value) && array_is_list($value)) {
foreach ($value as $key => $v) {
$v['_type'] ??= $arrayType;
$subValidators = [...$subValidators, ...$arrayType::makeValidator($v, $prefix . $paramName . '.' . $key . '.')];
}
}
$validator = [...$validator, ...$subValidators];
} else {
$subValidators = [$paramName . '.*' => $arrayType];
$validator = [...$validator, ...$subValidators];
}
}
}
}
return $validator;
}
public static function validate(array $array): void
{
$validator = static::makeValidator($array);
Validator::make($array, $validator)->validate();
}
public static function fromRequest(Request $request): static
{
$data = $request->all();
static::validate($data);
return static::from($data);
}
private static function getValueWithName(array|object $input, string $name): mixed
{
if (is_array($input)) return $input[$name] ?? null;
else {
try {
return $input->$name;
} catch (ErrorException) {
return null;
}
}
}
private static function getValue(array|object $input, string $name): mixed
{
$value = static::getValueWithName($input, $name);
if ($value !== null) return $value;
else return static::getValueWithName($input, Str::snake($name));
}
public static function from(array|string|object $input): static
{
$type = null;
// Convert to array if not array
if (is_string($input)) $input = json_decode($input, true);
if (is_object($input)) {
$type = get_class($input);
}
// Get the right type
if (!is_subclass_of($type, static::class)) {
$type = static::getValue($input, '_type') ?? static::class;
}
$constructor = new ReflectionClass($type)->getConstructor();
if ($constructor === null) return new $type();
// The params that will be used in the constructor
$params = [];
// Loop on the constructor parameters and get the value in $params
$constructorParameters = $constructor->getParameters();
foreach ($constructorParameters as &$param) {
$name = $param->getName();
$paramType = $param->getType(); // ReflectionNamedType|ReflectionUnionType|ReflectionIntersectionType|null
// We don't work with Union and Intersection types
if ($paramType instanceof ReflectionIntersectionType) {
throw new IntersectionTypeCannotBeUnserializedException();
} elseif ($paramType instanceof ReflectionUnionType) {
throw new UnionTypeCannotBeUnserializedException();
}
// Find the right way to use the value
$valueFromInput = static::getValue($input, $name);
// If we don't have the value, use default value if available or sets null if nullable
// If not, throw properly (to avoid throwing when trying to instantiate the class later)
if ($valueFromInput === null) {
if ($param->isDefaultValueAvailable()) {
$params[$name] = $param->getDefaultValue();
continue;
} elseif ($param->allowsNull()) {
$params[$name] = null;
continue;
} else {
throw new MissingPropertyException($name, $type);
}
}
if ($paramType instanceof ReflectionNamedType) {
$typeName = $paramType->getName();
$elementFromArrayType = gettype($valueFromInput);
$typeCast = static::getTypeCast($param);;
if ($typeCast !== null) {
$params[] = $typeCast->unserialize($valueFromInput);
continue;
}
if (in_array($typeName, ['bool', 'int', 'float', 'string'])) {
if (!static::isSameType($elementFromArrayType, $typeName)) throw new TypesDoNotMatchException($typeName, $elementFromArrayType);
} elseif ($typeName == 'array') {
if ($elementFromArrayType !== 'array') throw new TypesDoNotMatchException($typeName, $elementFromArrayType);
$attributes = $param->getAttributes(ArrayType::class);
$arrayType = count($attributes) === 0
? Serializable::class
: $attributes[0]->newInstance()->type;
if ($arrayType !== 'mixed') {
if (class_exists($arrayType)) {
foreach ($valueFromInput as &$v) {
$v = $arrayType::from($v);
}
} else {
foreach ($valueFromInput as &$v) {
if (!static::isSameType(gettype($v), $arrayType)) throw new TypesDoNotMatchException($arrayType, gettype($v));
}
}
}
} elseif (class_exists($typeName)) {
$valueFromInput = $typeName::from($valueFromInput);
}
}
$params[] = $valueFromInput;
}
return new $type(...$params);
}
public function toResponse($request)
{
return new JsonResponse(
data: $this->toArray(),
status: $request->isMethod(Request::METHOD_POST) ? Response::HTTP_CREATED : Response::HTTP_OK
);
}
public static function collect(iterable $iterable): array
{
$result = [];
foreach ($iterable as $item) {
$result[] = static::from($item);
}
return $result;
}
private static function isSameType(string $a, string $b): bool
{
return static::normalize($a) === static::normalize($b);
}
private static function normalize(string $type): string
{
return match (strtolower($type)) {
'int', 'integer' => 'int',
'bool', 'boolean' => 'bool',
'float', 'double', 'real' => 'float',
'string' => 'string',
'array' => 'array',
'object' => 'object',
'null' => 'null',
'mixed' => 'mixed',
'callable' => 'callable',
default => $type, // pour les classes, interfaces, etc.
};
}
}