diff --git a/src/BaseRequest.php b/src/BaseRequest.php index 1fa7638..cba3853 100644 --- a/src/BaseRequest.php +++ b/src/BaseRequest.php @@ -4,6 +4,7 @@ use Illuminate\Support\Arr; use Illuminate\Foundation\Http\FormRequest; +use RonasIT\Support\Exceptions\InvalidModelException; class BaseRequest extends FormRequest { @@ -42,6 +43,17 @@ public function onlyValidated($keys = null, $default = null): array return $validatedFields; } + protected function getOrderableFields(string $modelName, array $additionalFields = []): string + { + if (!class_exists($modelName)) { + throw new InvalidModelException("The model {$modelName} does not exist."); + } + + $fields = array_merge($modelName::getFields(), $additionalFields); + + return implode(',', $fields); + } + protected function filterOnlyValidated($fields, $validation): array { $result = []; diff --git a/tests/BaseRequestTest.php b/tests/BaseRequestTest.php new file mode 100644 index 0000000..ff003eb --- /dev/null +++ b/tests/BaseRequestTest.php @@ -0,0 +1,39 @@ +getMethod('getOrderableFields'); + $result = $method->invoke($baseRequest, TestModel::class); + + $modelFields = 'id,name,json_field,castable_field,*,created_at,updated_at'; + + $this->assertEquals($modelFields, $result); + } + + public function testGetOrderableFieldsWithAdditionalFields() + { + $baseRequest = new BaseRequest(); + $reflectionClass = new ReflectionClass($baseRequest); + + $method = $reflectionClass->getMethod('getOrderableFields'); + $result = $method->invoke($baseRequest, TestModel::class, ['additional_field_1', 'additional_field_2']); + + $modelAndAdditionalFields = 'id,name,json_field,castable_field,*,created_at,updated_at,additional_field_1,additional_field_2'; + + $this->assertEquals($modelAndAdditionalFields, $result); + } +}