|
2 | 2 |
|
3 | 3 | namespace Lomkit\Rest\Concerns\Resource; |
4 | 4 |
|
| 5 | +use Illuminate\Support\Facades\App; |
| 6 | +use Illuminate\Support\Str; |
5 | 7 | use Lomkit\Rest\Http\Requests\RestRequest; |
| 8 | +use Lomkit\Rest\Relations\Relation; |
6 | 9 |
|
7 | 10 | trait ConfiguresRestParameters |
8 | 11 | { |
@@ -38,45 +41,26 @@ public function getFields(\Lomkit\Rest\Http\Requests\RestRequest $request): arra |
38 | 41 | } |
39 | 42 |
|
40 | 43 | /** |
41 | | - * Get nested fields by prefixing them with a given prefix. |
| 44 | + * Verify the field is correct including nested relations. |
42 | 45 | * |
43 | | - * @param RestRequest $request |
44 | | - * @param string $prefix |
45 | | - * @param array $loadedRelations |
| 46 | + * @param string $field |
46 | 47 | * |
47 | | - * @return array |
| 48 | + * @return bool |
48 | 49 | */ |
49 | | - public function getNestedFields(RestRequest $request, string $prefix = '', array $loadedRelations = []) |
| 50 | + public function isNestedField(string $field, Relation $relation = null) |
50 | 51 | { |
51 | | - if ($prefix !== '') { |
52 | | - $prefix = $prefix.'.'; |
53 | | - } |
| 52 | + if (Str::contains($field, '.')) { |
| 53 | + // In case we are on a pivot we look for the relation pivot fields |
| 54 | + if (Str::before($field, '.') === 'pivot') { |
| 55 | + return method_exists($relation, 'getPivotFields') && in_array(Str::after($field, '.'), $relation->getPivotFields()); |
| 56 | + } |
54 | 57 |
|
55 | | - $fields = array_map( |
56 | | - function ($field) use ($prefix) { |
57 | | - return $prefix.$field; |
58 | | - }, |
59 | | - $this->getFields($request) |
60 | | - ); |
| 58 | + $fieldRelation = $this->relation(Str::before($field, '.')); |
61 | 59 |
|
62 | | - foreach ( |
63 | | - collect($this->getRelations($request)) |
64 | | - ->filter(function ($relation) use ($loadedRelations) { |
65 | | - return !in_array($relation->relation, $loadedRelations); |
66 | | - }) |
67 | | - as $relation |
68 | | - ) { |
69 | | - $loadedRelations[] = $relation->relation; |
70 | | - array_push( |
71 | | - $fields, |
72 | | - ...$relation->resource()->getNestedFields($request, $prefix.$relation->relation, $loadedRelations), |
73 | | - // We push the pivot fields if they exists |
74 | | - ...collect(method_exists($relation, 'getPivotFields') ? $relation->getPivotFields() : []) |
75 | | - ->map(function ($field) use ($relation, $prefix) { return $prefix.$relation->relation.'.pivot.'.$field; }) |
76 | | - ); |
| 60 | + return $fieldRelation->resource()->isNestedField(Str::after($field, '.'), $fieldRelation); |
77 | 61 | } |
78 | 62 |
|
79 | | - return $fields; |
| 63 | + return in_array($field, $this->getFields(App::make(RestRequest::class))); |
80 | 64 | } |
81 | 65 |
|
82 | 66 | /** |
|
0 commit comments