1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cerbero\LaravelDto\Factories; |
4
|
|
|
|
5
|
|
|
use Cerbero\Dto\DtoPropertiesMapper; |
6
|
|
|
use Cerbero\LaravelDto\Dto; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
|
9
|
|
|
use const Cerbero\Dto\NONE; |
|
|
|
|
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* The DTO factory. |
13
|
|
|
* |
14
|
|
|
*/ |
15
|
|
|
class DtoFactory implements DtoFactoryContract |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* The token indicating that a property is missing. Workaround to distinguish between NULL and missing values |
19
|
|
|
* |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
protected const MISSING_PROPERTY_TOKEN = 'cerbero_laravel_dto_missing_property_token'; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Retrieve an instance of the given DTO with data from the provided source. |
26
|
|
|
* |
27
|
|
|
* @param string $dto |
28
|
|
|
* @param mixed $source |
29
|
|
|
* @param int $flags |
30
|
|
|
* @return Dto |
31
|
|
|
*/ |
32
|
3 |
|
public function make(string $dto, $source, int $flags = NONE): Dto |
33
|
|
|
{ |
34
|
3 |
|
$data = []; |
35
|
3 |
|
$properties = DtoPropertiesMapper::for($dto)->getNames(); |
36
|
|
|
|
37
|
3 |
|
foreach ($properties as $property) { |
38
|
3 |
|
$value = $this->getPropertyFromSource($property, $source); |
39
|
|
|
|
40
|
3 |
|
if ($value === static::MISSING_PROPERTY_TOKEN) { |
41
|
2 |
|
continue; |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
$data[$property] = $value; |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
return $dto::make($data, $flags); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Retrieve the given property from the provided source |
52
|
|
|
* |
53
|
|
|
* @param string $property |
54
|
|
|
* @param mixed $source |
55
|
|
|
* @return mixed |
56
|
|
|
*/ |
57
|
3 |
|
protected function getPropertyFromSource(string $property, $source) |
58
|
|
|
{ |
59
|
3 |
|
$accessor = 'get' . Str::studly($property); |
60
|
|
|
|
61
|
3 |
|
if (method_exists($this, $accessor)) { |
62
|
1 |
|
return call_user_func([$this, $accessor], $source, $property); |
63
|
|
|
} |
64
|
|
|
|
65
|
3 |
|
return $this->getPropertyValueFromSource($property, $source); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Retrieve the value for the given property from the provided source |
70
|
|
|
* |
71
|
|
|
* @param string $property |
72
|
|
|
* @param mixed $source |
73
|
|
|
* @return mixed |
74
|
|
|
*/ |
75
|
2 |
|
protected function getPropertyValueFromSource(string $property, $source) |
76
|
|
|
{ |
77
|
2 |
|
$snakeProperty = Str::snake($property); |
78
|
2 |
|
$camelProperty = Str::camel($property); |
79
|
|
|
|
80
|
2 |
|
return data_get($source, $snakeProperty, data_get($source, $camelProperty, static::MISSING_PROPERTY_TOKEN)); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|