-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Make.php
60 lines (50 loc) · 1.49 KB
/
Make.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
<?php
namespace TgWebValid\Make;
use Carbon\Carbon;
use ReflectionNamedType;
use ReflectionProperty;
use TgWebValid\Support\Arrayable;
abstract class Make extends Arrayable
{
/**
* @param array<string, int|string|bool> $props
*/
public function __construct(array $props = [])
{
foreach ($props as $prop => $value) {
$value = match ($prop) {
'auth_date' => Carbon::createFromTimestamp((int) $value),
default => $value
};
$this->setProperty(camelize($prop), $value);
}
}
protected function setProperty(string $property, mixed $value): void
{
if(!property_exists(get_class($this), $property)) {
return;
}
$reflection = new ReflectionProperty(get_class($this), $property);
$type = $reflection->getType();
if(!($type instanceof ReflectionNamedType) || $type->isBuiltin()) {
$this->$property = $value;
return;
}
$class = $type->getName();
$this->$property = is_subclass_of($class, self::class)
? new $class($this->tryParseJSON($value))
: $value;
}
/**
* @return array<string, int|string|bool>
*/
protected function tryParseJSON(mixed $data): array
{
if(is_string($data)) {
/** @var array<string, int|string|bool> $assoc */
$assoc = json_decode($data, true);
return $assoc;
}
return [];
}
}