|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Cerbero\LaravelDto\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Cerbero\Dto\Exceptions\DtoNotFoundException; |
|
6
|
|
|
use Cerbero\LaravelDto\Dto; |
|
7
|
|
|
use Cerbero\LaravelDto\Factories\DtoFactory; |
|
8
|
|
|
use Cerbero\LaravelDto\Factories\DtoFactoryContract; |
|
9
|
|
|
use Cerbero\LaravelDto\Factories\ModelDtoFactory; |
|
10
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
11
|
|
|
use InvalidArgumentException; |
|
12
|
|
|
|
|
13
|
|
|
use const Cerbero\Dto\CAST_PRIMITIVES; |
|
|
|
|
|
|
14
|
|
|
use const Cerbero\Dto\NONE; |
|
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* The trait to turn an object into a DTO. |
|
18
|
|
|
* |
|
19
|
|
|
*/ |
|
20
|
|
|
trait TurnsIntoDto |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* Retrieve a DTO instance based on the current object data. |
|
24
|
|
|
* |
|
25
|
|
|
* @param string|int|null $dto |
|
26
|
|
|
* @param int $flags |
|
27
|
|
|
* @return Dto |
|
28
|
|
|
* @throws InvalidArgumentException |
|
29
|
|
|
* @throws DtoNotFoundException |
|
30
|
|
|
*/ |
|
31
|
15 |
|
public function toDto($dto = null, int $flags = NONE): Dto |
|
32
|
|
|
{ |
|
33
|
15 |
|
$flags = is_int($dto) ? $dto : $flags; |
|
34
|
15 |
|
$flags |= $this instanceof Model ? CAST_PRIMITIVES : NONE; |
|
35
|
15 |
|
$dto = $this->getDtoToTurnInto($dto); |
|
36
|
|
|
|
|
37
|
9 |
|
return $this->getDtoFactory()->make($dto, $this, $flags); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Retrieve the DTO class to turn the current object into |
|
42
|
|
|
* |
|
43
|
|
|
* @param mixed $dto |
|
44
|
|
|
* @return string |
|
45
|
|
|
* @throws InvalidArgumentException |
|
46
|
|
|
* @throws DtoNotFoundException |
|
47
|
|
|
*/ |
|
48
|
15 |
|
protected function getDtoToTurnInto($dto): string |
|
49
|
|
|
{ |
|
50
|
15 |
|
$dto = is_string($dto) ? $dto : $this->getDtoClass(); |
|
51
|
|
|
|
|
52
|
15 |
|
if (!$dto) { |
|
53
|
3 |
|
throw new InvalidArgumentException('DTO to turn [' . static::class . '] into not specified'); |
|
54
|
12 |
|
} elseif (!is_subclass_of($dto, Dto::class)) { |
|
55
|
3 |
|
throw new DtoNotFoundException($dto); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
9 |
|
return $dto; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Retrieve the DTO class |
|
63
|
|
|
* |
|
64
|
|
|
* @return string|null |
|
65
|
|
|
*/ |
|
66
|
6 |
|
protected function getDtoClass(): ?string |
|
67
|
|
|
{ |
|
68
|
6 |
|
return $this->dtoClass; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Retrieve the DTO assembler |
|
73
|
|
|
* |
|
74
|
|
|
* @return DtoFactoryContract |
|
75
|
|
|
*/ |
|
76
|
6 |
|
protected function getDtoFactory(): DtoFactoryContract |
|
77
|
|
|
{ |
|
78
|
6 |
|
return $this instanceof Model ? new ModelDtoFactory() : new DtoFactory(); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|