cerbero90 /
laravel-dto
| 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; |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 14 | use const Cerbero\Dto\NONE; |
||
|
0 ignored issues
–
show
|
|||
| 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 | 5 | public function toDto($dto = null, int $flags = NONE): Dto |
|
| 32 | { |
||
| 33 | 5 | $flags = is_int($dto) ? $dto : $flags; |
|
| 34 | 5 | $flags |= $this instanceof Model ? CAST_PRIMITIVES : NONE; |
|
| 35 | 5 | $dto = $this->getDtoToTurnInto($dto); |
|
| 36 | |||
| 37 | 3 | 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 | 5 | protected function getDtoToTurnInto($dto): string |
|
| 49 | { |
||
| 50 | 5 | $dto = is_string($dto) ? $dto : $this->getDtoClass(); |
|
| 51 | |||
| 52 | 5 | if (!$dto) { |
|
| 53 | 1 | throw new InvalidArgumentException('Unable to turn [' . static::class . '] into DTO, no class specified'); |
|
| 54 | 4 | } elseif (!is_subclass_of($dto, Dto::class)) { |
|
| 55 | 1 | throw new DtoNotFoundException($dto); |
|
| 56 | } |
||
| 57 | |||
| 58 | 3 | return $dto; |
|
| 59 | } |
||
| 60 | |||
| 61 | /** |
||
| 62 | * Retrieve the DTO class |
||
| 63 | * |
||
| 64 | * @return string|null |
||
| 65 | */ |
||
| 66 | 2 | protected function getDtoClass(): ?string |
|
| 67 | { |
||
| 68 | 2 | return $this->dtoClass; |
|
| 69 | } |
||
| 70 | |||
| 71 | /** |
||
| 72 | * Retrieve the DTO assembler |
||
| 73 | * |
||
| 74 | * @return DtoFactoryContract |
||
| 75 | */ |
||
| 76 | 2 | protected function getDtoFactory(): DtoFactoryContract |
|
| 77 | { |
||
| 78 | 2 | return $this instanceof Model ? new ModelDtoFactory() : new DtoFactory(); |
|
| 79 | } |
||
| 80 | } |
||
| 81 |