Skip to content

Commit

Permalink
Merge pull request #164 from RonasIT/161-ability-to-validate-order-by…
Browse files Browse the repository at this point in the history
…-field

#161: Ability to validate order_by field
  • Loading branch information
DenTray authored Dec 17, 2024
2 parents f9478a5 + 238b447 commit dca711f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/BaseRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Support\Arr;
use Illuminate\Foundation\Http\FormRequest;
use RonasIT\Support\Exceptions\InvalidModelException;

class BaseRequest extends FormRequest
{
Expand Down Expand Up @@ -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 = [];
Expand Down
39 changes: 39 additions & 0 deletions tests/BaseRequestTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace RonasIT\Support\Tests;

use ReflectionClass;
use RonasIT\Support\BaseRequest;
use RonasIT\Support\Tests\Support\Mock\TestModel;
use RonasIT\Support\Tests\Support\Traits\TableTestStateMockTrait;

class BaseRequestTest extends HelpersTestCase
{
use TableTestStateMockTrait;

public function testGetOrderableFields()
{
$baseRequest = new BaseRequest();
$reflectionClass = new ReflectionClass($baseRequest);

$method = $reflectionClass->getMethod('getOrderableFields');
$result = $method->invoke($baseRequest, TestModel::class);

$expectedResult = 'id,name,json_field,castable_field,*,created_at,updated_at';

$this->assertEquals($expectedResult, $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']);

$expectedResult = 'id,name,json_field,castable_field,*,created_at,updated_at,additional_field_1,additional_field_2';

$this->assertEquals($expectedResult, $result);
}
}

0 comments on commit dca711f

Please sign in to comment.