|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CodebarAg\Bexio\Dto\ManualEntries; |
| 4 | + |
| 5 | +use Exception; |
| 6 | +use Illuminate\Support\Arr; |
| 7 | +use Saloon\Http\Response; |
| 8 | +use Spatie\LaravelData\Data; |
| 9 | + |
| 10 | +class ManualEntryDTO extends Data |
| 11 | +{ |
| 12 | + public function __construct( |
| 13 | + public int $id, |
| 14 | + public string $type, |
| 15 | + public string $date, |
| 16 | + public string $name, |
| 17 | + public string $reference_number, |
| 18 | + public int $created_by_user_id, |
| 19 | + public int $edited_by_user_id, |
| 20 | + public array $entries, |
| 21 | + public bool $is_locked, |
| 22 | + public string $locked_info, |
| 23 | + ) { |
| 24 | + } |
| 25 | + |
| 26 | + public static function fromResponse(Response $response): self |
| 27 | + { |
| 28 | + if ($response->failed()) { |
| 29 | + throw new \Exception('Failed to create DTO from Response'); |
| 30 | + } |
| 31 | + |
| 32 | + $data = $response->json(); |
| 33 | + |
| 34 | + return self::fromArray($data); |
| 35 | + } |
| 36 | + |
| 37 | + public static function fromArray(array $data): self |
| 38 | + { |
| 39 | + if (! $data) { |
| 40 | + throw new Exception('Unable to create DTO. Data missing from response.'); |
| 41 | + } |
| 42 | + |
| 43 | + return new self( |
| 44 | + id: Arr::get($data, 'id'), |
| 45 | + type: Arr::get($data, 'type'), |
| 46 | + date: Arr::get($data, 'date'), |
| 47 | + name: Arr::get($data, 'name'), |
| 48 | + reference_number: Arr::get($data, 'reference_number'), |
| 49 | + created_by_user_id: Arr::get($data, 'created_by_user_id'), |
| 50 | + edited_by_user_id: Arr::get($data, 'edited_by_user_id'), |
| 51 | + entries: Arr::get($data, 'entries'), |
| 52 | + is_locked: Arr::get($data, 'is_locked'), |
| 53 | + locked_info: Arr::get($data, 'locked_info'), |
| 54 | + ); |
| 55 | + } |
| 56 | +} |
0 commit comments