|
2 | 2 |
|
3 | 3 | namespace Grixu\ApiClient\Data; |
4 | 4 |
|
5 | | -use ErrorException; |
6 | 5 | use Grixu\ApiClient\Contracts\ResponseParser; |
7 | | -use Illuminate\Support\Carbon; |
8 | 6 | use Illuminate\Support\Collection; |
| 7 | +use Illuminate\Support\Str; |
9 | 8 | use ReflectionClass; |
10 | 9 | use ReflectionProperty; |
11 | 10 |
|
@@ -42,23 +41,31 @@ protected function parseElement(array $input): array |
42 | 41 | $data = []; |
43 | 42 |
|
44 | 43 | foreach ($this->fields as $field) { |
45 | | - /** @var ReflectionProperty $field */ |
46 | | - $type = $field->getType()->getName(); |
47 | | - $fieldName = $field->getName(); |
48 | | - |
49 | | - try { |
50 | | - if (str_contains($type, 'Enum')) { |
51 | | - $data[$fieldName] = new $type($input[$fieldName]); |
52 | | - } elseif ($type === 'Illuminate\Support\Carbon') { |
53 | | - $data[$fieldName] = Carbon::createFromTimeString($input[$fieldName]); |
54 | | - } else { |
55 | | - $data[$fieldName] = $input[$fieldName]; |
56 | | - } |
57 | | - } catch (ErrorException) { |
58 | | - $data[$fieldName] = null; |
| 44 | + $dtoFieldName = $field->getName(); |
| 45 | + $arrayFieldName = Str::snake($dtoFieldName); |
| 46 | + |
| 47 | + if ($dtoFieldName === 'relationships') { |
| 48 | + $data[$dtoFieldName] = $this->parseRelationship($input[$arrayFieldName]); |
| 49 | + } else { |
| 50 | + $data[$dtoFieldName] = $input[$arrayFieldName] ?? null; |
59 | 51 | } |
60 | 52 | } |
61 | 53 |
|
62 | 54 | return $data; |
63 | 55 | } |
| 56 | + |
| 57 | + protected function parseRelationship(array $inputRelationships): array |
| 58 | + { |
| 59 | + $relationships = []; |
| 60 | + |
| 61 | + foreach ($inputRelationships as $input) { |
| 62 | + $relationship = []; |
| 63 | + foreach ($input as $key => $value) { |
| 64 | + $relationship[Str::camel($key)] = $value; |
| 65 | + } |
| 66 | + $relationships[] = $relationship; |
| 67 | + } |
| 68 | + |
| 69 | + return $relationships; |
| 70 | + } |
64 | 71 | } |
0 commit comments