install data table

This commit is contained in:
2026-05-04 14:52:54 +03:30
parent b24b61c754
commit 264ed1ecb9
28 changed files with 989 additions and 3 deletions

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Facades\DataTable;
use App\Services\DataTable\DataTableInput;
use App\Services\DataTable\DataTableService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Database\Query\Builder;
use Illuminate\Http\Request;
use App\Services\DataTable\Exceptions\InvalidParameterInterface;
class DataTable
{
/**
* Extracts data from request, passes to datatable service and prepares data for response.
* @param Model|Builder $mixed
* @param Request $request
* @param array $allowedFilters
* @param array $allowedRelations
* @param array $allowedSortings
* @param array $allowedSelects
* @return array
* @throws InvalidParameterInterface if input parameters are invalid.
*/
public function run(
Model|Builder $mixed,
Request $request,
array $allowedFilters = [],
array $allowedRelations = [],
array $allowedSortings = [],
array $allowedSelects = [],
array $allowedGroupBy = []
): array
{
$filters = json_decode($request->filters);
$sorting = json_decode($request->sorting);
$rels = $request->rels ?: array();
$dataTableInput = new DataTableInput(
$request->start,
$request->size,
$filters,
$sorting,
$rels,
$allowedFilters,
$allowedSortings,
$allowedGroupBy
);
$query = $this->makeQueryFromModel($mixed);
$dataTableService = (new DataTableService($query, $dataTableInput))
->setAllowedFilters($allowedFilters)
->setAllowedRelations($allowedRelations)
->setAllowedSortings($allowedSortings)
->setAllowedSelects($allowedSelects)
->setAllowedGroupBy($allowedGroupBy);
return $dataTableService->getData();
}
protected function makeQueryFromModel(Model|Builder $mixed): Builder
{
return ($mixed instanceof Model) ? $mixed->query() : $mixed;
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Facades\DataTable;
use Illuminate\Support\Facades\Facade;
class DataTableFacade extends Facade
{
protected static function getFacadeAccessor(): string
{
return DataTable::class;
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Providers;
use App\Facades\DataTable\DataTable;
use Illuminate\Support\ServiceProvider;
class DataTableServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
$this->app->bind('datatable', function () {
return new DataTable();
});
}
/**
* Bootstrap services.
*/
public function boot(): void
{
//
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Services\DataTable;
use App\Services\DataTable\Filter\Filter;
use App\Services\DataTable\Sort\Sort;
class DataTableInput
{
/**
* @param int $start
* @param int $size
* @param array $filters
* @param array $sorting
* @param array $rels
*/
public function __construct(
private ?int $start,
private ?int $size,
private array $filters,
private ?array $sorting,
private array $rels,
private array $allowedFilters,
private array $allowedSortings,
private ?array $GroupBy,
)
{
}
public function getStart(): ?int
{
return $this->start;
}
public function getSize(): ?int
{
return $this->size;
}
/**
* @return array returns an array of Filter objects
*/
public function getFilters(): array
{
$filters = array();
foreach ($this->filters as $filter) {
$filters[] = new Filter(
$filter->id,
$filter->value,
$filter->fn,
$filter->datatype,
$this->allowedFilters
);
}
return $filters;
}
/**
* @return array
*/
public function getSorting(): ?array
{
$sorts = [];
if (!empty($this->sorting)){
foreach ($this->sorting as $sort) {
$sorts[] = new Sort($sort->id, $sort->desc, $this->allowedSortings);
}
}
return $sorts;
}
public function getRelations(): array
{
return $this->rels;
}
public function getGroupBy(): ?array
{
return $this->GroupBy;
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace App\Services\DataTable;
use App\Services\DataTable\Filter\ApplyFilter;
use App\Services\DataTable\Sort\ApplySort;
use Illuminate\Contracts\Database\Query\Builder;
class DataTableService
{
protected array $allowedFilters;
protected array $allowedRelations;
protected array $allowedSortings;
protected array $allowedSelects;
protected array $allowedGroupBy;
private int $totalRowCount;
public function __construct(
protected Builder $query,
private DataTableInput $dataTableInput
)
{
}
public function setAllowedFilters(array $allowedFilters): DataTableService
{
$this->allowedFilters = $allowedFilters;
return $this;
}
public function setAllowedRelations(array $allowedRelations): DataTableService
{
$this->allowedRelations = $allowedRelations;
return $this;
}
public function setAllowedSortings(array $allowedSortings): DataTableService
{
$this->allowedSortings = $allowedSortings;
return $this;
}
public function setAllowedSelects(array $allowedSelects): DataTableService
{
$this->allowedSelects = $allowedSelects;
return $this;
}
public function setAllowedGroupBy(array $allowedGroupBy): DataTableService
{
$this->allowedGroupBy = $allowedGroupBy;
return $this;
}
/**
* Handle 'getData' operations
* @return array
*/
public function getData(): array
{
$query = $this->buildQuery();
$data = $query->get();
return array(
'data' => $data,
'meta' => [
'totalRowCount' => $this->totalRowCount
]
);
}
protected function buildQuery(): Builder
{
$query = $this->query;
foreach ($this->dataTableInput->getFilters() as $filter) {
$query = (new ApplyFilter($query, $filter))->apply();
}
$query = $this->applySelect($query, $this->allowedSelects);
$query = $this->includeRelationsInQuery($query, $this->allowedRelations);
$query = $this->applyGroupBy($query, $this->allowedGroupBy);
$this->totalRowCount = $query->count();
if (!is_null($this->dataTableInput->getStart())) {
$query->offset($this->dataTableInput->getStart());
}
if(!is_null($this->dataTableInput->getSize())){
$query->limit($this->dataTableInput->getSize());
}
$sorting = $this->dataTableInput->getSorting();
foreach ($sorting as $sort){
$query = (new ApplySort($query, $sort))->apply();
}
return $query;
}
protected function applySelect(Builder $query, array $selectedFields): Builder
{
if (!empty($selectedFields)) {
$query->select($selectedFields);
}
return $query;
}
protected function applyGroupBy(Builder $query, array $groupBy): Builder
{
return empty($groupBy) ? $query : $query->groupBy($groupBy);
}
protected function includeRelationsInQuery(Builder $query, array $rels): Builder
{
if (!empty($rels)) {
$query->with($rels);
}
return $query;
}
// (later) define mapping of relation names to prevent relation name expose.
// (later) define mapping of column names to prevent column name expose.
}

View File

@@ -0,0 +1,15 @@
<?php
namespace App\Services\DataTable\Enums;
enum DataType: string
{
case NUMERIC = 'numeric';
case TEXT = 'text';
case DATE = 'date';
public static function values(): array
{
return array_column(self::cases(), 'value');
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Services\DataTable\Enums;
enum SearchType: string
{
case CONTAINS = 'contains';
case EQUALS = 'equals';
case NOT_EQUALS = 'notEquals';
case BETWEEN = 'between';
case GREATER_THAN = 'greaterThan';
case LESS_THAN = 'lessThan';
case FUZZY = 'fuzzy';
public static function values(): array
{
return array_column(self::cases(), 'value');
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Services\DataTable\Exceptions;
use Exception;
class InvalidFilterException extends Exception implements InvalidParameterInterface
{
protected $fieldName;
public function __construct($fieldName, $message = "", $code = 400, \Throwable $previous = null)
{
$this->fieldName = $fieldName;
parent::__construct($message, $code, $previous);
}
public function getFieldName()
{
return $this->fieldName;
}
}

View File

@@ -0,0 +1,7 @@
<?php
namespace App\Services\DataTable\Exceptions;
interface InvalidParameterInterface
{
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Services\DataTable\Exceptions;
use Exception;
class InvalidRelationException extends Exception implements InvalidParameterInterface
{
protected $fieldName;
public function __construct($fieldName, $message = "", $code = 400, \Throwable $previous = null)
{
$this->fieldName = $fieldName;
parent::__construct($message, $code, $previous);
}
public function getFieldName()
{
return $this->fieldName;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Services\DataTable\Exceptions;
use Exception;
class InvalidSortingException extends Exception implements InvalidParameterInterface
{
protected $fieldName;
public function __construct($fieldName, $message = "", $code = 400, \Throwable $previous = null)
{
$this->fieldName = $fieldName;
parent::__construct($message, $code, $previous);
}
public function getFieldName()
{
return $this->fieldName;
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace App\Services\DataTable\Filter;
use App\Services\DataTable\Enums\SearchType;
use App\Services\DataTable\Exceptions\InvalidFilterException;
use App\Services\DataTable\Filter\SearchFunctions\FilterBetween;
use App\Services\DataTable\Filter\SearchFunctions\FilterContains;
use App\Services\DataTable\Filter\SearchFunctions\FilterEquals;
use App\Services\DataTable\Filter\SearchFunctions\FilterGreaterThan;
use App\Services\DataTable\Filter\SearchFunctions\FilterLessThan;
use App\Services\DataTable\Filter\SearchFunctions\FilterNotEquals;
use App\Services\DataTable\Filter\SearchFunctions\SearchFilter;
use Illuminate\Contracts\Database\Query\Builder;
class ApplyFilter
{
private SearchFilter $searchFilter;
/**
* @param Builder $query
* @param Filter $filter
*/
public function __construct(
private Builder $query,
private Filter $filter,
)
{
}
public function apply(): Builder
{
$filter = $this->filter;
$query = $this->query;
$searchType = SearchType::from($filter->getFn());
switch ($searchType) {
case SearchType::CONTAINS:
$this->searchFilter = new FilterContains($query, $filter);
break;
case SearchType::EQUALS:
$this->searchFilter = new FilterEquals($query, $filter);
break;
case SearchType::NOT_EQUALS:
$this->searchFilter = new FilterNotEquals($query, $filter);
break;
case SearchType::BETWEEN:
$this->searchFilter = new FilterBetween($query, $filter);
break;
case SearchType::GREATER_THAN:
$this->searchFilter = new FilterGreaterThan($query, $filter);
break;
case SearchType::LESS_THAN:
$this->searchFilter = new FilterLessThan($query, $filter);
break;
default:
$searchFunction = $filter->getFn();
throw new InvalidFilterException($searchFunction, "search function `$searchFunction` is invalid.");
}
$relation = $this->filter->getRelation();
return method_exists($this->query->getModel(), $relation) ? $this->applyFilterToRelation($relation) : $this->searchFilter->apply();
}
protected function applyFilterToRelation(string $relation): Builder
{
return $this->query->whereHas($relation, function (Builder $query) {
$this->filter->removeRelationFromId();
$this->applyFilter($query, $this->filter);
});
}
private function applyFilter(Builder $query, Filter $filter): Builder
{
return (new ApplyFilter($query, $filter))->apply();
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace App\Services\DataTable\Filter;
use App\Services\DataTable\Validators\FilterValidator;
class Filter
{
private static FilterValidator $filterValidator;
/**
* @param string $id
* @param string|int|array $value
* @param string $fn
* @param string $datatype
* @param array $allowedFilters
* @throws \App\Services\DataTable\Exceptions\InvalidFilterException
*/
public function __construct(
private string $id,
private string|int|array $value,
private string $fn,
private string $datatype,
private array $allowedFilters
)
{
self::$filterValidator = FilterValidator::getInstance();
self::$filterValidator->isValid($this, $this->allowedFilters);
}
public function getId(): string
{
return $this->id;
}
public function getValue(): array|int|string
{
return $this->value;
}
public function getFn(): string
{
return $this->fn;
}
public function getDatatype(): string
{
return $this->datatype;
}
public function getRelation(): string
{
$fieldArray = explode('.', $this->id);
return count($fieldArray) > 1 ? $fieldArray[0] : '';
}
public function getColumn(): string
{
$fieldArray = explode('.', $this->id);
return array_pop($fieldArray);
}
public function removeRelationFromId(): void
{
$this->id = $this->getColumn();
}
public function setValue(int|array|string $value): void
{
$this->value = $value;
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use Illuminate\Contracts\Database\Query\Builder;
class FilterBetween extends SearchFilter
{
public function apply(): Builder
{
$query = $this->query;
[$minVal, $maxVal] = $this->filter->getValue();
if ($minVal) {
if ($this->filter->getDatatype() == "date") {
$minVal = $minVal . " 00:00:00";
}
$this->filter->setValue($minVal);
$query = (new FilterGreaterThanOrEqual($this->query, $this->filter))->apply();
}
if ($maxVal) {
if ($this->filter->getDatatype() == "date") {
$maxVal = $maxVal . " 23:59:59";
}
$this->filter->setValue($maxVal);
$query = (new FilterLessThanOrEqual($this->query, $this->filter))->apply();
}
return $query;
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use App\Services\DataTable\Enums\DataType;
use Illuminate\Contracts\Database\Query\Builder;
class FilterContains extends SearchFilter
{
public function apply(): Builder
{
$column = $this->filter->getId();
$value = '%' . $this->filter->getValue() . '%';
if ($this->filter->getDatatype() == DataType::TEXT->value) {
$query = $this->searchIgnoreCase($column, $value);
} else {
$query = $this->query->where($column, 'LIKE', $value);
}
return $query;
}
private function searchIgnoreCase(string $column, string $value): Builder
{
$value = strtolower($value);
return $this->query->whereRaw("LOWER($column) LIKE ?", [$value]);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use App\Services\DataTable\Enums\DataType;
use Illuminate\Contracts\Database\Query\Builder;
class FilterEquals extends SearchFilter
{
public function apply(): Builder
{
$column = $this->filter->getId();
$value = $this->filter->getValue();
if ($this->filter->getDatatype() == DataType::TEXT->value) {
$query = $this->searchIgnoreCase($column, $value);
} else {
$query = $this->query->where($column, $value);
}
return $query;
}
private function searchIgnoreCase(string $column, string $value): Builder
{
$value = strtolower($value);
return $this->query->whereRaw("LOWER($column) = ?", [$value]);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use App\Services\DataTable\Enums\DataType;
use Illuminate\Contracts\Database\Query\Builder;
class FilterGreaterThan extends SearchFilter
{
public function apply(): Builder
{
$value = ($this->filter->getDatatype() == DataType::NUMERIC) ?
(float)$this->filter->getValue() : $this->filter->getValue();
return $this->query->where($this->filter->getId(), '>', $value);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use App\Services\DataTable\Enums\DataType;
use Illuminate\Contracts\Database\Query\Builder;
class FilterGreaterThanOrEqual extends SearchFilter
{
public function apply(): Builder
{
$value = ($this->filter->getDatatype() == DataType::NUMERIC) ?
(float)$this->filter->getValue() : $this->filter->getValue();
return $this->query->where($this->filter->getId(), '>=', $value);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use App\Services\DataTable\Enums\DataType;
use Illuminate\Contracts\Database\Query\Builder;
class FilterLessThan extends SearchFilter
{
public function apply(): Builder
{
$value = ($this->filter->getDatatype() == DataType::NUMERIC) ?
(float)$this->filter->getValue() : $this->filter->getValue();
return $this->query->where($this->filter->getId(), '<', $value);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use App\Services\DataTable\Enums\DataType;
use Illuminate\Contracts\Database\Query\Builder;
class FilterLessThanOrEqual extends SearchFilter
{
public function apply(): Builder
{
$value = ($this->filter->getDatatype() == DataType::NUMERIC) ?
(float)$this->filter->getValue() : $this->filter->getValue();
return $this->query->where($this->filter->getId(), '<=', $value);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use Illuminate\Contracts\Database\Query\Builder;
class FilterNotEquals extends SearchFilter
{
public function apply(): Builder
{
$column = $this->filter->getId();
$value = $this->filter->getValue();
return $this->query->whereNot($column, $value);
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Services\DataTable\Filter\SearchFunctions;
use App\Services\DataTable\Filter\Filter;
use Illuminate\Contracts\Database\Query\Builder;
abstract class SearchFilter
{
/**
* @param Builder $query
* @param Filter $filter
*/
public function __construct(
protected Builder $query,
protected Filter $filter,
)
{
}
abstract public function apply(): Builder;
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Services\DataTable\Sort;
use Illuminate\Contracts\Database\Query\Builder;
class ApplySort
{
/**
* @param Builder $query
* @param ?Sort $sort
*/
public function __construct(
private Builder $query,
private ?Sort $sort,
)
{
}
public function apply(): Builder
{
$query = $this->query;
if (!is_null($this->sort)) {
$query->orderBy($this->sort->getId(), $this->sort->getDirection());
}
return $query;
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Services\DataTable\Sort;
use App\Services\DataTable\Validators\SortingValidator;
class Sort
{
private static SortingValidator $sortingValidator;
/**
* @param string $id
* @param bool $desc
* @param array $allowedSortings
* @throws \App\Services\DataTable\Exceptions\InvalidSortingException
*/
public function __construct(
private string $id,
private bool $desc,
private array $allowedSortings,
)
{
self::$sortingValidator = SortingValidator::getInstance();
self::$sortingValidator->isValid($this, $this->allowedSortings);
}
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
public function getDirection(): string
{
return $this->desc === true ? 'desc' : 'asc';
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Services\DataTable\Validators;
use App\Services\DataTable\Enums\SearchType;
use App\Services\DataTable\Enums\DataType;
use App\Services\DataTable\Exceptions\InvalidFilterException;
use App\Services\DataTable\Filter\Filter;
class FilterValidator
{
private static $instance;
private function __construct()
{
}
public static function getInstance(): FilterValidator
{
if (!isset(self::$instance)) {
self::$instance = new static();
}
return self::$instance;
}
public function isValid(Filter $filter, array $allowedFilters): bool
{
if (!$this->isAllowed($filter, $allowedFilters)) {
$filterId = $filter->getId();
throw new InvalidFilterException($filter->getId(), "filtering field `$filterId` is not allowed.");
}
if (!$this->isValidSearchFunction($filter)) {
$searchFunction = $filter->getFn();
throw new InvalidFilterException($searchFunction, "search function `$searchFunction` is invalid.");
}
if ($this->isValidDataType($filter) == -1) {
throw new InvalidFilterException(null, "datatype property is not set in `filters` array.");
}
if (!$this->isValidDataType($filter)) {
$datatype = $filter->getDatatype();
throw new InvalidFilterException($datatype, "datatype `$datatype` is invalid.");
}
return true;
}
protected function isAllowed(Filter $filter, array $allowedFilters): bool
{
return $allowedFilters == ['*'] || in_array($filter->getId(), $allowedFilters);
}
protected function isValidSearchFunction(Filter $filter): bool
{
$searchFunction = $filter->getFn();
return isset($searchFunction) && in_array($searchFunction, SearchType::values());
}
protected function isValidDataType(Filter $filter): int
{
if (!property_exists($filter, 'datatype'))
return -1;
return $filter->getDatatype() && in_array($filter->getDatatype(), DataType::values()) ? 1 : 0;
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Services\DataTable\Validators;
use App\Services\DataTable\Exceptions\InvalidRelationException;
class RelationValidator
{
public static function validate(?array $rels, array $allowedRelations): bool
{
foreach ($rels as $relation) {
if (!self::isAllowed($relation, $allowedRelations)) {
throw new InvalidRelationException($relation, "relation `$relation` is not allowed.");
}
}
return true;
}
public static function isAllowed(string $relation, array $allowedRelations): bool
{
return !$relation || in_array($relation, $allowedRelations);
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Services\DataTable\Validators;
use App\Services\DataTable\Exceptions\InvalidSortingException;
use App\Services\DataTable\Sort\Sort;
class SortingValidator
{
private static $instance;
private function __construct()
{
}
public static function getInstance(): SortingValidator
{
if (!isset(self::$instance)) {
self::$instance = new static();
}
return self::$instance;
}
public function isValid(Sort $sorting, array $allowedSortings): bool
{
if (!$this->isAllowed($sorting, $allowedSortings)) {
$sortId = $sorting->getId();
throw new InvalidSortingException($sortId, "sorting field `$sortId` is not allowed.");
}
return true;
}
protected function isAllowed(Sort $sorting, array $allowedSortings): bool
{
return $allowedSortings == ['*'] || in_array($sorting->getId(), $allowedSortings);
}
}

View File

@@ -1,7 +1,6 @@
<?php
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
App\Providers\AppServiceProvider::class,
App\Providers\DataTableServiceProvider::class,
];