first commit
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables;
|
||||
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
|
||||
class ApiResourceDataTable extends CollectionDataTable
|
||||
{
|
||||
/**
|
||||
* Can the DataTable engine be created with these parameters.
|
||||
*
|
||||
* @param mixed $source
|
||||
* @return bool
|
||||
*/
|
||||
public static function canCreate($source)
|
||||
{
|
||||
return $source instanceof AnonymousResourceCollection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method, create and return an instance for the DataTable engine.
|
||||
*
|
||||
* @param \Illuminate\Http\Resources\Json\AnonymousResourceCollection<array-key, array>|array $source
|
||||
* @return ApiResourceDataTable|DataTableAbstract
|
||||
*/
|
||||
public static function create($source)
|
||||
{
|
||||
return parent::create($source);
|
||||
}
|
||||
|
||||
/**
|
||||
* CollectionEngine constructor.
|
||||
*
|
||||
* @param \Illuminate\Http\Resources\Json\AnonymousResourceCollection<array-key, array> $resourceCollection
|
||||
*/
|
||||
public function __construct(AnonymousResourceCollection $resourceCollection)
|
||||
{
|
||||
/** @var \Illuminate\Support\Collection<(int|string), array> $collection */
|
||||
$collection = collect($resourceCollection)->pluck('resource');
|
||||
$this->request = app('datatables.request');
|
||||
$this->config = app('datatables.config');
|
||||
$this->collection = $collection;
|
||||
$this->original = $collection;
|
||||
$this->columns = array_keys($this->serialize($collection->first()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Illuminate\Contracts\Support\Arrayable;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Str;
|
||||
use Yajra\DataTables\Utilities\Helper;
|
||||
|
||||
class CollectionDataTable extends DataTableAbstract
|
||||
{
|
||||
/**
|
||||
* Collection object.
|
||||
*
|
||||
* @var \Illuminate\Support\Collection<array-key, array>
|
||||
*/
|
||||
public Collection $original;
|
||||
|
||||
/**
|
||||
* The offset of the first record in the full dataset.
|
||||
*/
|
||||
private int $offset = 0;
|
||||
|
||||
/**
|
||||
* CollectionEngine constructor.
|
||||
*
|
||||
* @param \Illuminate\Support\Collection<array-key, array> $collection
|
||||
*/
|
||||
public function __construct(public Collection $collection)
|
||||
{
|
||||
$this->request = app('datatables.request');
|
||||
$this->config = app('datatables.config');
|
||||
$this->original = $this->collection;
|
||||
$this->columns = array_keys($this->serialize($this->collection->first()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize collection.
|
||||
*/
|
||||
protected function serialize(mixed $collection): array
|
||||
{
|
||||
return $collection instanceof Arrayable ? $collection->toArray() : (array) $collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Can the DataTable engine be created with these parameters.
|
||||
*
|
||||
* @param mixed $source
|
||||
* @return bool
|
||||
*/
|
||||
public static function canCreate($source)
|
||||
{
|
||||
return is_array($source) || $source instanceof Collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method, create and return an instance for the DataTable engine.
|
||||
*
|
||||
* @param AnonymousResourceCollection|array|\Illuminate\Support\Collection<array-key, array> $source
|
||||
* @return static
|
||||
*/
|
||||
public static function create($source)
|
||||
{
|
||||
if (is_array($source)) {
|
||||
$source = new Collection($source);
|
||||
}
|
||||
|
||||
return parent::create($source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count results.
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return $this->collection->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform column search.
|
||||
*/
|
||||
public function columnSearch(): void
|
||||
{
|
||||
for ($i = 0, $c = count($this->request->columns()); $i < $c; $i++) {
|
||||
$column = $this->getColumnName($i);
|
||||
|
||||
if (is_null($column)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->request->isColumnSearchable($i) || $this->isBlacklisted($column)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$regex = $this->request->isRegex($i);
|
||||
$keyword = $this->request->columnKeyword($i);
|
||||
|
||||
$this->collection = $this->collection->filter(
|
||||
function ($row) use ($column, $keyword, $regex) {
|
||||
$data = $this->serialize($row);
|
||||
|
||||
/** @var string $value */
|
||||
$value = Arr::get($data, $column);
|
||||
|
||||
if ($this->config->isCaseInsensitive()) {
|
||||
if ($regex) {
|
||||
return preg_match('/'.$keyword.'/i', $value) == 1;
|
||||
}
|
||||
|
||||
return str_contains(Str::lower($value), Str::lower($keyword));
|
||||
}
|
||||
|
||||
if ($regex) {
|
||||
return preg_match('/'.$keyword.'/', $value) == 1;
|
||||
}
|
||||
|
||||
return str_contains($value, $keyword);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform pagination.
|
||||
*/
|
||||
public function paging(): void
|
||||
{
|
||||
$offset = $this->request->start() - $this->offset;
|
||||
$length = $this->request->length() > 0 ? $this->request->length() : 10;
|
||||
|
||||
$this->collection = $this->collection->slice($offset, $length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Organizes works.
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function make(bool $mDataSupport = true): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->validateMinLengthSearch();
|
||||
|
||||
$this->totalRecords = $this->totalCount();
|
||||
|
||||
if ($this->totalRecords) {
|
||||
$results = $this->results();
|
||||
$processed = $this->processResults($results, $mDataSupport);
|
||||
$output = $this->transform($results, $processed);
|
||||
|
||||
$this->collection = collect($output);
|
||||
$this->ordering();
|
||||
$this->filterRecords();
|
||||
$this->paginate();
|
||||
|
||||
$this->revertIndexColumn($mDataSupport);
|
||||
}
|
||||
|
||||
return $this->render($this->collection->values()->all());
|
||||
} catch (Exception $exception) {
|
||||
return $this->errorResponse($exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get results.
|
||||
*
|
||||
* @return \Illuminate\Support\Collection<array-key, array>
|
||||
*/
|
||||
public function results(): Collection
|
||||
{
|
||||
return $this->collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revert transformed DT_RowIndex back to its original values.
|
||||
*
|
||||
* @param bool $mDataSupport
|
||||
*/
|
||||
private function revertIndexColumn($mDataSupport): void
|
||||
{
|
||||
if ($this->columnDef['index']) {
|
||||
$indexColumn = (string) Config::get('datatables.index_column', 'DT_RowIndex');
|
||||
/** @var int|string $index */
|
||||
$index = $mDataSupport ? $indexColumn : 0;
|
||||
$start = $this->request->start();
|
||||
$indexEdits = $mDataSupport ? $this->getIndexColumnEdits($indexColumn) : [];
|
||||
|
||||
$this->collection->transform(function ($data) use ($index, &$start, $mDataSupport, $indexColumn, $indexEdits) {
|
||||
$data[$index] = ++$start;
|
||||
|
||||
if ($mDataSupport && $indexEdits !== []) {
|
||||
foreach ($indexEdits as $content) {
|
||||
$data[$indexColumn] = Helper::compileContent($content, $data, $data);
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get edit templates/callbacks registered for the index column.
|
||||
*/
|
||||
private function getIndexColumnEdits(string $indexColumn): array
|
||||
{
|
||||
$edits = [];
|
||||
foreach ($this->columnDef['edit'] ?? [] as $column) {
|
||||
if (($column['name'] ?? null) === $indexColumn) {
|
||||
$edits[] = $column['content'];
|
||||
}
|
||||
}
|
||||
|
||||
return $edits;
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the offset of the first item of the collection with respect to
|
||||
* the FULL dataset the collection was sliced from. It effectively allows the
|
||||
* collection to be "pre-sliced".
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function setOffset(int $offset): self
|
||||
{
|
||||
$this->offset = $offset;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform global search for the given keyword.
|
||||
*/
|
||||
protected function globalSearch(string $keyword): void
|
||||
{
|
||||
$keyword = $this->config->isCaseInsensitive() ? Str::lower($keyword) : $keyword;
|
||||
|
||||
$this->collection = $this->collection->filter(function ($row) use ($keyword) {
|
||||
$data = $this->serialize($row);
|
||||
foreach ($this->request->searchableColumnIndex() as $index) {
|
||||
$column = $this->getColumnName($index);
|
||||
$value = Arr::get($data, $column);
|
||||
if (is_bool($value)) {
|
||||
$value = $value ? '1' : '0';
|
||||
} elseif (! is_scalar($value) && ! $value instanceof \Stringable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = (string) $value;
|
||||
$value = $this->config->isCaseInsensitive() ? Str::lower($value) : $value;
|
||||
|
||||
if (Str::contains($value, $keyword)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform default query orderBy clause.
|
||||
*/
|
||||
protected function defaultOrdering(): void
|
||||
{
|
||||
$criteria = $this->request->orderableColumns();
|
||||
if (! empty($criteria)) {
|
||||
$sorter = $this->getSorter($criteria);
|
||||
|
||||
$this->collection = $this->collection
|
||||
->map(fn ($data) => Arr::dot($data))
|
||||
->sort($sorter)
|
||||
->map(function ($data) {
|
||||
foreach ($data as $key => $value) {
|
||||
unset($data[$key]);
|
||||
Arr::set($data, $key, $value);
|
||||
}
|
||||
|
||||
return $data;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get array sorter closure.
|
||||
*/
|
||||
protected function getSorter(array $criteria): Closure
|
||||
{
|
||||
return function ($a, $b) use ($criteria) {
|
||||
foreach ($criteria as $orderable) {
|
||||
$column = $this->getColumnName($orderable['column']);
|
||||
$direction = $orderable['direction'];
|
||||
if ($direction === 'desc') {
|
||||
$first = $b;
|
||||
$second = $a;
|
||||
} else {
|
||||
$first = $a;
|
||||
$second = $b;
|
||||
}
|
||||
if (is_numeric($first[$column] ?? null) && is_numeric($second[$column] ?? null)) {
|
||||
if ($first[$column] < $second[$column]) {
|
||||
$cmp = -1;
|
||||
} elseif ($first[$column] > $second[$column]) {
|
||||
$cmp = 1;
|
||||
} else {
|
||||
$cmp = 0;
|
||||
}
|
||||
} elseif ($this->config->isCaseInsensitive()) {
|
||||
$cmp = strnatcasecmp($first[$column] ?? '', $second[$column] ?? '');
|
||||
} else {
|
||||
$cmp = strnatcmp($first[$column] ?? '', $second[$column] ?? '');
|
||||
}
|
||||
if ($cmp != 0) {
|
||||
return $cmp;
|
||||
}
|
||||
}
|
||||
|
||||
// all elements were equal
|
||||
return 0;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve callback parameter instance.
|
||||
*
|
||||
* @return array<int|string, mixed>
|
||||
*/
|
||||
protected function resolveCallbackParameter(): array
|
||||
{
|
||||
return [$this, false];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Contracts;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
interface DataTable
|
||||
{
|
||||
/**
|
||||
* Get results.
|
||||
*
|
||||
* @return \Illuminate\Support\Collection<int, \stdClass>|\Illuminate\Support\Collection<array-key, array>
|
||||
*/
|
||||
public function results(): Collection;
|
||||
|
||||
/**
|
||||
* Count results.
|
||||
*/
|
||||
public function count(): int;
|
||||
|
||||
/**
|
||||
* Count total items.
|
||||
*/
|
||||
public function totalCount(): int;
|
||||
|
||||
/**
|
||||
* Set auto filter off and run your own filter.
|
||||
* Overrides global search.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function filter(callable $callback, bool $globalSearch = false): self;
|
||||
|
||||
/**
|
||||
* Perform global search.
|
||||
*/
|
||||
public function filtering(): void;
|
||||
|
||||
/**
|
||||
* Perform column search.
|
||||
*/
|
||||
public function columnSearch(): void;
|
||||
|
||||
/**
|
||||
* Perform pagination.
|
||||
*/
|
||||
public function paging(): void;
|
||||
|
||||
/**
|
||||
* Perform sorting of columns.
|
||||
*/
|
||||
public function ordering(): void;
|
||||
|
||||
/**
|
||||
* Organizes works.
|
||||
*/
|
||||
public function make(bool $mDataSupport = true): JsonResponse;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Contracts;
|
||||
|
||||
interface Formatter
|
||||
{
|
||||
/**
|
||||
* @param array|\Illuminate\Database\Eloquent\Model|object $row
|
||||
* @return string
|
||||
*/
|
||||
public function format(mixed $value, $row);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables;
|
||||
|
||||
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
|
||||
use Illuminate\Contracts\Database\Query\Builder as QueryBuilder;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Traits\Macroable;
|
||||
use Yajra\DataTables\Exceptions\Exception;
|
||||
use Yajra\DataTables\Utilities\Config as DataTablesConfig;
|
||||
use Yajra\DataTables\Utilities\Request;
|
||||
|
||||
class DataTables
|
||||
{
|
||||
use Macroable;
|
||||
|
||||
/**
|
||||
* DataTables request object.
|
||||
*/
|
||||
protected Utilities\Request $request;
|
||||
|
||||
/**
|
||||
* Make a DataTable instance from source.
|
||||
* Alias of make for backward compatibility.
|
||||
*
|
||||
* @param object $source
|
||||
* @return DataTableAbstract
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
public static function of($source)
|
||||
{
|
||||
return self::make($source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a DataTable instance from source.
|
||||
*
|
||||
* @param object $source
|
||||
* @return DataTableAbstract
|
||||
*
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
public static function make($source)
|
||||
{
|
||||
$engines = Config::get('datatables.engines', []);
|
||||
$builders = Config::get('datatables.builders', []);
|
||||
|
||||
$args = func_get_args();
|
||||
foreach ($builders as $class => $engine) {
|
||||
if (is_string($class) && $source instanceof $class) {
|
||||
/** @var int|string $engineKey */
|
||||
$engineKey = is_int($engine) || is_string($engine) ? $engine : (string) $engine;
|
||||
$callback = [$engines[$engineKey], 'create'];
|
||||
|
||||
if (is_callable($callback)) {
|
||||
/** @var \Yajra\DataTables\DataTableAbstract $instance */
|
||||
$instance = call_user_func_array($callback, $args);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($engines as $engine) {
|
||||
$canCreate = [$engine, 'canCreate'];
|
||||
if (is_callable($canCreate) && call_user_func_array($canCreate, $args)) {
|
||||
$create = [$engine, 'create'];
|
||||
|
||||
if (is_callable($create)) {
|
||||
/** @var \Yajra\DataTables\DataTableAbstract $instance */
|
||||
$instance = call_user_func_array($create, $args);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('No available engine for '.$source::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get request object.
|
||||
*/
|
||||
public function getRequest(): Request
|
||||
{
|
||||
return app('datatables.request');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get config instance.
|
||||
*/
|
||||
public function getConfig(): DataTablesConfig
|
||||
{
|
||||
return app('datatables.config');
|
||||
}
|
||||
|
||||
/**
|
||||
* DataTables using query builder.
|
||||
*
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
public function query(QueryBuilder $builder): QueryDataTable
|
||||
{
|
||||
$dataTable = (string) Config::get('datatables.engines.query');
|
||||
|
||||
$this->validateDataTable($dataTable, QueryDataTable::class);
|
||||
|
||||
return $dataTable::create($builder);
|
||||
}
|
||||
|
||||
/**
|
||||
* DataTables using Eloquent Builder.
|
||||
*
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
public function eloquent(EloquentBuilder $builder): EloquentDataTable
|
||||
{
|
||||
$dataTable = (string) Config::get('datatables.engines.eloquent');
|
||||
|
||||
$this->validateDataTable($dataTable, EloquentDataTable::class);
|
||||
|
||||
return $dataTable::create($builder);
|
||||
}
|
||||
|
||||
/**
|
||||
* DataTables using Collection.
|
||||
*
|
||||
* @param \Illuminate\Support\Collection<array-key, array>|array $collection
|
||||
*
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
public function collection($collection): CollectionDataTable
|
||||
{
|
||||
$dataTable = (string) Config::get('datatables.engines.collection');
|
||||
|
||||
$this->validateDataTable($dataTable, CollectionDataTable::class);
|
||||
|
||||
return $dataTable::create($collection);
|
||||
}
|
||||
|
||||
/**
|
||||
* DataTables using Collection.
|
||||
*
|
||||
* @param \Illuminate\Http\Resources\Json\AnonymousResourceCollection<array-key, array>|array $resource
|
||||
* @return ApiResourceDataTable|DataTableAbstract
|
||||
*/
|
||||
public function resource($resource)
|
||||
{
|
||||
return ApiResourceDataTable::create($resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
public function validateDataTable(string $engine, string $parent): void
|
||||
{
|
||||
if (! ($engine == $parent || is_subclass_of($engine, $parent))) {
|
||||
throw new Exception("The given datatable engine `$engine` is not compatible with `$parent`.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables;
|
||||
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Support\Str;
|
||||
use Yajra\DataTables\Utilities\Config as DataTablesConfig;
|
||||
use Yajra\DataTables\Utilities\Request;
|
||||
|
||||
class DataTablesServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register the service provider.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
if ($this->isLumen()) {
|
||||
require_once 'lumen.php';
|
||||
}
|
||||
|
||||
$this->setupAssets();
|
||||
|
||||
$this->app->alias('datatables', DataTables::class);
|
||||
$this->app->singleton('datatables', fn () => new DataTables);
|
||||
|
||||
$this->app->singleton('datatables.request', fn () => new Request);
|
||||
|
||||
$this->app->singleton('datatables.config', DataTablesConfig::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Boot the instance, add macros for datatable engines.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function boot()
|
||||
{
|
||||
$engines = Config::get('datatables.engines', []);
|
||||
foreach ($engines as $engine => $class) {
|
||||
$engine = Str::camel($engine);
|
||||
|
||||
if (! method_exists(DataTables::class, $engine) && ! DataTables::hasMacro($engine)) {
|
||||
DataTables::macro($engine, function () use ($class) {
|
||||
$canCreate = [$class, 'canCreate'];
|
||||
if (is_callable($canCreate) && ! call_user_func_array($canCreate, func_get_args())) {
|
||||
throw new \InvalidArgumentException;
|
||||
}
|
||||
|
||||
$create = [$class, 'create'];
|
||||
if (is_callable($create)) {
|
||||
return call_user_func_array($create, func_get_args());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup package assets.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function setupAssets()
|
||||
{
|
||||
$this->mergeConfigFrom($config = __DIR__.'/config/datatables.php', 'datatables');
|
||||
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->publishes([$config => config_path('datatables.php')], 'datatables');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if app uses Lumen.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function isLumen()
|
||||
{
|
||||
return Str::contains($this->app->version(), 'Lumen');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables;
|
||||
|
||||
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
|
||||
use Illuminate\Database\Eloquent\Relations\MorphTo;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Yajra\DataTables\Exceptions\Exception;
|
||||
|
||||
/**
|
||||
* @property EloquentBuilder $query
|
||||
*/
|
||||
class EloquentDataTable extends QueryDataTable
|
||||
{
|
||||
/**
|
||||
* Flag to enable the generation of unique table aliases on eagerly loaded join columns.
|
||||
* You may want to enable it if you encounter a "Not unique table/alias" error when performing a search or applying ordering.
|
||||
*/
|
||||
protected bool $enableEagerJoinAliases = false;
|
||||
|
||||
/**
|
||||
* EloquentEngine constructor.
|
||||
*/
|
||||
public function __construct(Model|EloquentBuilder $model)
|
||||
{
|
||||
$builder = match (true) {
|
||||
$model instanceof Model => $model->newQuery(),
|
||||
$model instanceof Relation => $model->getQuery(),
|
||||
$model instanceof EloquentBuilder => $model,
|
||||
};
|
||||
|
||||
parent::__construct($builder->getQuery());
|
||||
|
||||
$this->query = $builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Can the DataTable engine be created with these parameters.
|
||||
*
|
||||
* @param mixed $source
|
||||
*/
|
||||
public static function canCreate($source): bool
|
||||
{
|
||||
return $source instanceof EloquentBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add columns in collection.
|
||||
*
|
||||
* @param bool|int $order
|
||||
* @return $this
|
||||
*/
|
||||
public function addColumns(array $names, $order = false)
|
||||
{
|
||||
foreach ($names as $name => $attribute) {
|
||||
if (is_int($name)) {
|
||||
$name = $attribute;
|
||||
}
|
||||
|
||||
$this->addColumn($name, fn ($model) => $model->getAttribute($attribute), is_int($order) ? $order++ : $order);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* If column name could not be resolved then use primary key.
|
||||
*/
|
||||
protected function getPrimaryKeyName(): string
|
||||
{
|
||||
return $this->query->getModel()->getKeyName();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
protected function compileQuerySearch($query, string $column, string $keyword, string $boolean = 'or', bool $nested = false): void
|
||||
{
|
||||
if (substr_count($column, '.') > 1) {
|
||||
$parts = explode('.', $column);
|
||||
$firstRelation = array_shift($parts);
|
||||
$column = implode('.', $parts);
|
||||
|
||||
if ($this->isMorphRelation($firstRelation)) {
|
||||
$query->{$boolean.'WhereHasMorph'}(
|
||||
$firstRelation,
|
||||
'*',
|
||||
function (EloquentBuilder $query) use ($column, $keyword) {
|
||||
parent::compileQuerySearch($query, $column, $keyword, '');
|
||||
}
|
||||
);
|
||||
} else {
|
||||
$query->{$boolean.'WhereHas'}($firstRelation, function (EloquentBuilder $query) use ($column, $keyword) {
|
||||
self::compileQuerySearch($query, $column, $keyword, '', true);
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$parts = explode('.', $column);
|
||||
$newColumn = array_pop($parts);
|
||||
$relation = implode('.', $parts);
|
||||
|
||||
if (! $nested && $this->isNotEagerLoaded($relation)) {
|
||||
parent::compileQuerySearch($query, $column, $keyword, $boolean);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->isMorphRelation($relation)) {
|
||||
$query->{$boolean.'WhereHasMorph'}(
|
||||
$relation,
|
||||
'*',
|
||||
function (EloquentBuilder $query) use ($newColumn, $keyword) {
|
||||
parent::compileQuerySearch($query, $newColumn, $keyword, '');
|
||||
}
|
||||
);
|
||||
} else {
|
||||
$query->{$boolean.'WhereHas'}($relation, function (EloquentBuilder $query) use ($newColumn, $keyword) {
|
||||
parent::compileQuerySearch($query, $newColumn, $keyword, '');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a relation was not used on eager loading.
|
||||
*
|
||||
* @param string $relation
|
||||
* @return bool
|
||||
*/
|
||||
protected function isNotEagerLoaded($relation)
|
||||
{
|
||||
return ! $relation
|
||||
|| ! array_key_exists($relation, $this->query->getEagerLoads())
|
||||
|| $relation === $this->query->getModel()->getTable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a relation is a morphed one or not.
|
||||
*
|
||||
* @param string $relation
|
||||
* @return bool
|
||||
*/
|
||||
protected function isMorphRelation($relation)
|
||||
{
|
||||
$isMorph = false;
|
||||
if ($relation !== null && $relation !== '') {
|
||||
$relationParts = explode('.', $relation);
|
||||
$firstRelation = array_shift($relationParts);
|
||||
$model = $this->query->getModel();
|
||||
$isMorph = method_exists($model, $firstRelation) && $model->$firstRelation() instanceof MorphTo;
|
||||
}
|
||||
|
||||
return $isMorph;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
protected function resolveRelationColumn(string $column): string
|
||||
{
|
||||
$parts = explode('.', $column);
|
||||
$columnName = array_pop($parts);
|
||||
$relation = preg_replace('/\[.*?\]/', '', implode('.', $parts));
|
||||
|
||||
if ($this->isNotEagerLoaded($relation)) {
|
||||
return parent::resolveRelationColumn($column);
|
||||
}
|
||||
|
||||
return $this->joinEagerLoadedColumn($relation, $columnName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Join eager loaded relation and get the related column name.
|
||||
*
|
||||
* @param string $relation
|
||||
* @param string $relationColumn
|
||||
* @return string
|
||||
*
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
protected function joinEagerLoadedColumn($relation, $relationColumn)
|
||||
{
|
||||
$tableAlias = $pivotAlias = '';
|
||||
$lastQuery = $this->query;
|
||||
foreach (explode('.', $relation) as $eachRelation) {
|
||||
$model = $lastQuery->getRelation($eachRelation);
|
||||
if ($this->enableEagerJoinAliases) {
|
||||
$lastAlias = $tableAlias ?: $this->getTablePrefix($lastQuery);
|
||||
$tableAlias = $tableAlias.'_'.$eachRelation;
|
||||
$pivotAlias = $tableAlias.'_pivot';
|
||||
} else {
|
||||
$lastAlias = $tableAlias ?: $lastQuery->getModel()->getTable();
|
||||
}
|
||||
switch (true) {
|
||||
case $model instanceof BelongsToMany:
|
||||
if ($this->enableEagerJoinAliases) {
|
||||
$pivot = $model->getTable().' as '.$pivotAlias;
|
||||
} else {
|
||||
$pivot = $pivotAlias = $model->getTable();
|
||||
}
|
||||
$pivotPK = $pivotAlias.'.'.$model->getForeignPivotKeyName();
|
||||
$pivotFK = ltrim($lastAlias.'.'.$model->getParentKeyName(), '.');
|
||||
$this->performJoin($pivot, $pivotPK, $pivotFK);
|
||||
|
||||
$related = $model->getRelated();
|
||||
if ($this->enableEagerJoinAliases) {
|
||||
$table = $related->getTable().' as '.$tableAlias;
|
||||
} else {
|
||||
$table = $tableAlias = $related->getTable();
|
||||
}
|
||||
$tablePK = $model->getRelatedPivotKeyName();
|
||||
$foreign = $pivotAlias.'.'.$tablePK;
|
||||
$other = $tableAlias.'.'.$related->getKeyName();
|
||||
|
||||
$lastQuery->addSelect($tableAlias.'.'.$relationColumn);
|
||||
|
||||
break;
|
||||
|
||||
case $model instanceof HasOneThrough:
|
||||
if ($this->enableEagerJoinAliases) {
|
||||
$pivot = explode('.', $model->getQualifiedParentKeyName())[0].' as '.$pivotAlias;
|
||||
} else {
|
||||
$pivot = $pivotAlias = explode('.', $model->getQualifiedParentKeyName())[0];
|
||||
}
|
||||
$pivotPK = $pivotAlias.'.'.$model->getFirstKeyName();
|
||||
$pivotFK = ltrim($lastAlias.'.'.$model->getLocalKeyName(), '.');
|
||||
$this->performJoin($pivot, $pivotPK, $pivotFK);
|
||||
|
||||
$related = $model->getRelated();
|
||||
if ($this->enableEagerJoinAliases) {
|
||||
$table = $related->getTable().' as '.$tableAlias;
|
||||
} else {
|
||||
$table = $tableAlias = $related->getTable();
|
||||
}
|
||||
$tablePK = $model->getSecondLocalKeyName();
|
||||
$foreign = $pivotAlias.'.'.$tablePK;
|
||||
$other = $tableAlias.'.'.$related->getKeyName();
|
||||
|
||||
$lastQuery->addSelect($lastQuery->getModel()->getTable().'.*');
|
||||
|
||||
break;
|
||||
|
||||
case $model instanceof HasOneOrMany:
|
||||
if ($this->enableEagerJoinAliases) {
|
||||
$table = $model->getRelated()->getTable().' as '.$tableAlias;
|
||||
} else {
|
||||
$table = $tableAlias = $model->getRelated()->getTable();
|
||||
}
|
||||
$foreign = $tableAlias.'.'.$model->getForeignKeyName();
|
||||
$other = ltrim($lastAlias.'.'.$model->getLocalKeyName(), '.');
|
||||
break;
|
||||
|
||||
case $model instanceof BelongsTo:
|
||||
if ($this->enableEagerJoinAliases) {
|
||||
$table = $model->getRelated()->getTable().' as '.$tableAlias;
|
||||
} else {
|
||||
$table = $tableAlias = $model->getRelated()->getTable();
|
||||
}
|
||||
$foreign = ltrim($lastAlias.'.'.$model->getForeignKeyName(), '.');
|
||||
$other = $tableAlias.'.'.$model->getOwnerKeyName();
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Exception('Relation '.$model::class.' is not yet supported.');
|
||||
}
|
||||
$this->performJoin($table, $foreign, $other);
|
||||
$lastQuery = $model->getQuery();
|
||||
}
|
||||
|
||||
return $tableAlias.'.'.$relationColumn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the generation of unique table aliases on eagerly loaded join columns.
|
||||
* You may want to enable it if you encounter a "Not unique table/alias" error when performing a search or applying ordering.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function enableEagerJoinAliases(): static
|
||||
{
|
||||
$this->enableEagerJoinAliases = true;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform join query.
|
||||
*
|
||||
* @param string $table
|
||||
* @param string $foreign
|
||||
* @param string $other
|
||||
* @param string $type
|
||||
*/
|
||||
protected function performJoin($table, $foreign, $other, $type = 'left'): void
|
||||
{
|
||||
$joins = [];
|
||||
$builder = $this->getBaseQueryBuilder();
|
||||
foreach ($builder->joins ?? [] as $join) {
|
||||
$joins[] = $join->table;
|
||||
}
|
||||
|
||||
if (! in_array($table, $joins)) {
|
||||
$this->getBaseQueryBuilder()->join($table, $foreign, '=', $other, $type);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Exceptions;
|
||||
|
||||
class Exception extends \Exception {}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Facades;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
|
||||
/**
|
||||
* @mixin \Yajra\DataTables\DataTables
|
||||
*
|
||||
* @method static \Yajra\DataTables\EloquentDataTable eloquent($builder)
|
||||
* @method static \Yajra\DataTables\QueryDataTable query($builder)
|
||||
* @method static \Yajra\DataTables\CollectionDataTable collection($collection)
|
||||
*
|
||||
* @see \Yajra\DataTables\DataTables
|
||||
*/
|
||||
class DataTables extends Facade
|
||||
{
|
||||
/**
|
||||
* Get the registered name of the component.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected static function getFacadeAccessor()
|
||||
{
|
||||
return 'datatables';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables;
|
||||
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class PaginatorDataTable extends CollectionDataTable
|
||||
{
|
||||
/**
|
||||
* @param LengthAwarePaginator<int, mixed> $paginator
|
||||
*/
|
||||
public function __construct(protected LengthAwarePaginator $paginator)
|
||||
{
|
||||
parent::__construct(collect($paginator->items()));
|
||||
|
||||
$this->skipPaging();
|
||||
}
|
||||
|
||||
/**
|
||||
* Can the DataTable engine be created with these parameters.
|
||||
*
|
||||
* @param mixed $source
|
||||
*/
|
||||
public static function canCreate($source): bool
|
||||
{
|
||||
return $source instanceof LengthAwarePaginator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Count total items from paginator.
|
||||
*/
|
||||
public function totalCount(): int
|
||||
{
|
||||
return $this->totalRecords ??= $this->paginator->total();
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip datatable-side filtering since the source is pre-paginated.
|
||||
*/
|
||||
protected function filterRecords(): void
|
||||
{
|
||||
$this->filteredRecords = $this->totalCount();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Processors;
|
||||
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Yajra\DataTables\Contracts\Formatter;
|
||||
use Yajra\DataTables\Utilities\Helper;
|
||||
|
||||
class DataProcessor
|
||||
{
|
||||
protected array $output = [];
|
||||
|
||||
/**
|
||||
* @var array<array-key, array{name: string, content: mixed}>
|
||||
*/
|
||||
protected array $appendColumns = [];
|
||||
|
||||
/**
|
||||
* @var array<array-key, array{name: string, content: mixed}>
|
||||
*/
|
||||
protected array $editColumns = [];
|
||||
|
||||
protected array $rawColumns = [];
|
||||
|
||||
/**
|
||||
* @var array|string[]
|
||||
*/
|
||||
protected array $exceptions = ['DT_RowId', 'DT_RowClass', 'DT_RowData', 'DT_RowAttr'];
|
||||
|
||||
protected array $onlyColumns = [];
|
||||
|
||||
protected array $makeHidden = [];
|
||||
|
||||
protected array $makeVisible = [];
|
||||
|
||||
protected array $excessColumns = [];
|
||||
|
||||
/**
|
||||
* @var string|array
|
||||
*/
|
||||
protected mixed $escapeColumns = [];
|
||||
|
||||
protected bool $includeIndex = false;
|
||||
|
||||
protected bool $ignoreGetters = false;
|
||||
|
||||
protected string $indexColumn;
|
||||
|
||||
public function __construct(protected iterable $results, array $columnDef, protected array $templates, protected int $start = 0)
|
||||
{
|
||||
$this->appendColumns = $columnDef['append'] ?? [];
|
||||
$this->editColumns = $columnDef['edit'] ?? [];
|
||||
$this->excessColumns = $columnDef['excess'] ?? [];
|
||||
$this->onlyColumns = $columnDef['only'] ?? [];
|
||||
$this->escapeColumns = $columnDef['escape'] ?? [];
|
||||
$this->includeIndex = $columnDef['index'] ?? false;
|
||||
$this->rawColumns = $columnDef['raw'] ?? [];
|
||||
$this->makeHidden = $columnDef['hidden'] ?? [];
|
||||
$this->makeVisible = $columnDef['visible'] ?? [];
|
||||
$this->ignoreGetters = $columnDef['ignore_getters'] ?? false;
|
||||
$this->indexColumn = (string) Config::get('datatables.index_column', 'DT_RowIndex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Process data to output on browser.
|
||||
*
|
||||
* @param bool $object
|
||||
*/
|
||||
public function process($object = false): array
|
||||
{
|
||||
$this->output = [];
|
||||
|
||||
foreach ($this->results as $row) {
|
||||
$data = Helper::convertToArray($row, ['hidden' => $this->makeHidden, 'visible' => $this->makeVisible, 'ignore_getters' => $this->ignoreGetters]);
|
||||
$value = $this->addColumns($data, $row);
|
||||
$value = $this->editColumns($value, $row);
|
||||
$value = $this->setupRowVariables($value, $row);
|
||||
$value = $this->selectOnlyNeededColumns($value);
|
||||
$value = $this->removeExcessColumns($value);
|
||||
|
||||
if ($this->includeIndex) {
|
||||
$value[$this->indexColumn] = ++$this->start;
|
||||
$value = $this->editIndexColumn($value, $row);
|
||||
}
|
||||
|
||||
$this->output[] = $object ? $value : $this->flatten($value);
|
||||
}
|
||||
|
||||
return $this->escapeColumns($this->output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process add columns.
|
||||
*
|
||||
* @param array|object|\Illuminate\Database\Eloquent\Model $row
|
||||
*/
|
||||
protected function addColumns(array $data, $row): array
|
||||
{
|
||||
foreach ($this->appendColumns as $value) {
|
||||
$content = $value['content'];
|
||||
if ($content instanceof Formatter) {
|
||||
$column = str_replace('_formatted', '', $value['name']);
|
||||
|
||||
$value['content'] = $content->format($data[$column], $row);
|
||||
if (isset($data[$column])) {
|
||||
$value['content'] = $content->format($data[$column], $row);
|
||||
}
|
||||
} else {
|
||||
$value['content'] = Helper::compileContent($content, $data, $row);
|
||||
}
|
||||
|
||||
$data = Helper::includeInArray($value, $data);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process edit columns.
|
||||
*/
|
||||
protected function editColumns(array $data, object|array $row): array
|
||||
{
|
||||
foreach ($this->editColumns as $value) {
|
||||
if ($this->includeIndex && $value['name'] === $this->indexColumn) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value['content'] = Helper::compileContent($value['content'], $data, $row);
|
||||
Arr::set($data, $value['name'], $value['content']);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit index column after it has been added to the row.
|
||||
*/
|
||||
protected function editIndexColumn(array $data, object|array $row): array
|
||||
{
|
||||
if (! $this->includeIndex) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
foreach ($this->editColumns as $value) {
|
||||
if ($value['name'] !== $this->indexColumn) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value['content'] = Helper::compileContent($value['content'], $data, $row);
|
||||
Arr::set($data, $this->indexColumn, $value['content']);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup additional DT row variables.
|
||||
*/
|
||||
protected function setupRowVariables(array $data, object|array $row): array
|
||||
{
|
||||
$processor = new RowProcessor($data, $row);
|
||||
|
||||
return $processor
|
||||
->rowValue('DT_RowId', $this->templates['DT_RowId'])
|
||||
->rowValue('DT_RowClass', $this->templates['DT_RowClass'])
|
||||
->rowData('DT_RowData', $this->templates['DT_RowData'])
|
||||
->rowData('DT_RowAttr', $this->templates['DT_RowAttr'])
|
||||
->getData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get only needed columns.
|
||||
*/
|
||||
protected function selectOnlyNeededColumns(array $data): array
|
||||
{
|
||||
if (empty($this->onlyColumns)) {
|
||||
return $data;
|
||||
} else {
|
||||
$results = [];
|
||||
foreach ($this->onlyColumns as $onlyColumn) {
|
||||
Arr::set($results, $onlyColumn, Arr::get($data, $onlyColumn));
|
||||
}
|
||||
foreach ($this->exceptions as $exception) {
|
||||
if ($column = Arr::get($data, $exception)) {
|
||||
Arr::set($results, $exception, $column);
|
||||
}
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove declared hidden columns.
|
||||
*/
|
||||
protected function removeExcessColumns(array $data): array
|
||||
{
|
||||
foreach ($this->excessColumns as $value) {
|
||||
Arr::forget($data, $value);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flatten array with exceptions.
|
||||
*/
|
||||
public function flatten(array $array): array
|
||||
{
|
||||
$return = [];
|
||||
foreach ($array as $key => $value) {
|
||||
if (in_array($key, $this->exceptions)) {
|
||||
$return[$key] = $value;
|
||||
} else {
|
||||
$return[] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape column values as declared.
|
||||
*/
|
||||
protected function escapeColumns(array $output): array
|
||||
{
|
||||
return array_map(function ($row) {
|
||||
if ($this->escapeColumns == '*') {
|
||||
$row = $this->escapeRow($row);
|
||||
} elseif (is_array($this->escapeColumns)) {
|
||||
$columns = array_diff($this->escapeColumns, $this->rawColumns);
|
||||
foreach ($columns as $key) {
|
||||
/** @var string $content */
|
||||
$content = Arr::get($row, $key);
|
||||
Arr::set($row, $key, e($content));
|
||||
}
|
||||
}
|
||||
|
||||
return $row;
|
||||
}, $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape all string or Htmlable values of row.
|
||||
*/
|
||||
protected function escapeRow(array $row): array
|
||||
{
|
||||
$arrayDot = array_filter(Arr::dot($row));
|
||||
foreach ($arrayDot as $key => $value) {
|
||||
if (! in_array($key, $this->rawColumns)) {
|
||||
$arrayDot[$key] = (is_string($value) || $value instanceof Htmlable) ? e($value) : $value;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($arrayDot as $key => $value) {
|
||||
Arr::set($row, $key, $value);
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Processors;
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
use Yajra\DataTables\Utilities\Helper;
|
||||
|
||||
class RowProcessor
|
||||
{
|
||||
/**
|
||||
* @param array|object $row
|
||||
*/
|
||||
public function __construct(protected array $data, protected $row) {}
|
||||
|
||||
/**
|
||||
* Process DT RowId and Class value.
|
||||
*
|
||||
* @param string $attribute
|
||||
* @param string|callable $template
|
||||
* @return $this
|
||||
*
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function rowValue($attribute, $template)
|
||||
{
|
||||
if (! empty($template)) {
|
||||
if (! is_callable($template) && Arr::get($this->data, $template)) {
|
||||
$this->data[$attribute] = Arr::get($this->data, $template);
|
||||
} else {
|
||||
$this->data[$attribute] = Helper::compileContent($template, $this->data, $this->row);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process DT Row Data and Attr.
|
||||
*
|
||||
* @param string $attribute
|
||||
* @return $this
|
||||
*
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public function rowData($attribute, array $template)
|
||||
{
|
||||
if (count($template)) {
|
||||
$this->data[$attribute] = [];
|
||||
foreach ($template as $key => $value) {
|
||||
$this->data[$attribute][$key] = Helper::compileContent($value, $this->data, $this->row);
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getData()
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Utilities;
|
||||
|
||||
use Illuminate\Contracts\Config\Repository;
|
||||
|
||||
class Config
|
||||
{
|
||||
/**
|
||||
* Config constructor.
|
||||
*/
|
||||
public function __construct(private readonly Repository $repository) {}
|
||||
|
||||
/**
|
||||
* Check if config uses wild card search.
|
||||
*/
|
||||
public function isWildcard(): bool
|
||||
{
|
||||
return (bool) $this->repository->get('datatables.search.use_wildcards', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if config uses smart search.
|
||||
*/
|
||||
public function isSmartSearch(): bool
|
||||
{
|
||||
return (bool) $this->repository->get('datatables.search.smart', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if config uses case-insensitive search.
|
||||
*/
|
||||
public function isCaseInsensitive(): bool
|
||||
{
|
||||
return (bool) $this->repository->get('datatables.search.case_insensitive', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if app is in debug mode.
|
||||
*/
|
||||
public function isDebugging(): bool
|
||||
{
|
||||
return (bool) $this->repository->get('app.debug', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the specified configuration value.
|
||||
*
|
||||
* @param string $key
|
||||
* @return mixed
|
||||
*/
|
||||
public function get($key, mixed $default = null)
|
||||
{
|
||||
return $this->repository->get($key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a given configuration value.
|
||||
*
|
||||
* @param array|string $key
|
||||
* @return void
|
||||
*/
|
||||
public function set($key, mixed $value = null)
|
||||
{
|
||||
$this->repository->set($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if dataTable config uses multi-term searching.
|
||||
*/
|
||||
public function isMultiTerm(): bool
|
||||
{
|
||||
return (bool) $this->repository->get('datatables.search.multi_term', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if dataTable config uses starts_with searching.
|
||||
*/
|
||||
public function isStartsWithSearch(): bool
|
||||
{
|
||||
return (bool) $this->repository->get('datatables.search.starts_with', false);
|
||||
}
|
||||
|
||||
public function jsonOptions(): int
|
||||
{
|
||||
/** @var int $options */
|
||||
$options = $this->repository->get('datatables.json.options', 0);
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
public function jsonHeaders(): array
|
||||
{
|
||||
return (array) $this->repository->get('datatables.json.header', []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Utilities;
|
||||
|
||||
use Closure;
|
||||
use DateTime;
|
||||
use Illuminate\Contracts\Support\Arrayable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Str;
|
||||
use ReflectionFunction;
|
||||
use ReflectionMethod;
|
||||
|
||||
class Helper
|
||||
{
|
||||
/**
|
||||
* Places item of extra columns into results by care of their order.
|
||||
*/
|
||||
public static function includeInArray(array $item, array $array): array
|
||||
{
|
||||
/** @var int|string $itemName */
|
||||
$itemName = is_int($item['name']) || is_string($item['name']) ? $item['name'] : (string) $item['name'];
|
||||
|
||||
if (self::isItemOrderInvalid($item, $array)) {
|
||||
return array_merge($array, [$itemName => $item['content']]);
|
||||
}
|
||||
|
||||
$count = 0;
|
||||
$last = $array;
|
||||
$first = [];
|
||||
foreach ($array as $key => $value) {
|
||||
if ($count == $item['order']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
unset($last[$key]);
|
||||
$first[$key] = $value;
|
||||
|
||||
$count++;
|
||||
}
|
||||
|
||||
return array_merge($first, [$itemName => $item['content']], $last);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if item order is valid.
|
||||
*/
|
||||
protected static function isItemOrderInvalid(array $item, array $array): bool
|
||||
{
|
||||
return $item['order'] === false || $item['order'] >= count($array);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the parameter of a callable thing (from is_callable) and returns it's arguments using reflection.
|
||||
*
|
||||
* @param callable $callable
|
||||
* @return \ReflectionParameter[]
|
||||
*
|
||||
* @throws \ReflectionException
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
private static function reflectCallableParameters($callable)
|
||||
{
|
||||
/*
|
||||
loosely after https://github.com/technically-php/callable-reflection/blob/main/src/CallableReflection.php#L72-L86.
|
||||
Licence is compatible, both project use MIT
|
||||
*/
|
||||
if ($callable instanceof Closure) {
|
||||
$reflection = new ReflectionFunction($callable);
|
||||
} elseif (is_string($callable) && function_exists($callable)) {
|
||||
$reflection = new ReflectionFunction($callable);
|
||||
} elseif (is_string($callable) && str_contains($callable, '::')) {
|
||||
$reflection = new ReflectionMethod($callable);
|
||||
} elseif (is_object($callable) && method_exists($callable, '__invoke')) {
|
||||
$reflection = new ReflectionMethod($callable, '__invoke');
|
||||
} else {
|
||||
throw new \InvalidArgumentException('argument is not callable or the code is wrong');
|
||||
}
|
||||
|
||||
return $reflection->getParameters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if content is callable or blade string, processes and returns.
|
||||
*
|
||||
* @param mixed $content Pre-processed content
|
||||
* @param array $data data to use with blade template
|
||||
* @param array|object $param parameter to call with callable
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \ReflectionException
|
||||
*/
|
||||
public static function compileContent(mixed $content, array $data, array|object $param)
|
||||
{
|
||||
if (is_string($content)) {
|
||||
return static::compileBlade($content, static::getMixedValue($data, $param));
|
||||
}
|
||||
|
||||
if (is_callable($content)) {
|
||||
$arguments = self::reflectCallableParameters($content);
|
||||
|
||||
if (count($arguments) > 0) {
|
||||
return app()->call($content, [$arguments[0]->name => $param]);
|
||||
}
|
||||
|
||||
return $content($param);
|
||||
}
|
||||
|
||||
if (is_array($content)) {
|
||||
[$view, $viewData] = $content;
|
||||
|
||||
return static::compileBlade($view, static::getMixedValue($data, $param) + $viewData);
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses and compiles strings by using Blade Template System.
|
||||
*
|
||||
*
|
||||
* @throws \Throwable
|
||||
*/
|
||||
public static function compileBlade(string $str, array $data = []): false|string
|
||||
{
|
||||
if (view()->exists($str)) {
|
||||
/** @var view-string $str */
|
||||
return view($str, $data)->render();
|
||||
}
|
||||
|
||||
return Blade::render($str, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a mixed value of custom data and the parameters.
|
||||
*/
|
||||
public static function getMixedValue(array $data, array|object $param): array
|
||||
{
|
||||
$casted = self::castToArray($param);
|
||||
|
||||
$data['model'] = $param;
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
if (isset($casted[$key])) {
|
||||
$data[$key] = $casted[$key];
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast the parameter into an array.
|
||||
*/
|
||||
public static function castToArray(array|object $param): array
|
||||
{
|
||||
if ($param instanceof Arrayable) {
|
||||
return $param->toArray();
|
||||
}
|
||||
|
||||
return (array) $param;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get equivalent or method of query builder.
|
||||
*/
|
||||
public static function getOrMethod(string $method): string
|
||||
{
|
||||
if (! Str::contains(Str::lower($method), 'or')) {
|
||||
return 'or'.ucfirst($method);
|
||||
}
|
||||
|
||||
return $method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts array object values to associative array.
|
||||
*/
|
||||
public static function convertToArray(mixed $row, array $filters = []): array
|
||||
{
|
||||
if (Arr::get($filters, 'ignore_getters') && is_object($row) && method_exists($row, 'getAttributes')) {
|
||||
$data = $row->getAttributes();
|
||||
if (method_exists($row, 'getRelations')) {
|
||||
foreach ($row->getRelations() as $relationName => $relation) {
|
||||
if (is_iterable($relation)) {
|
||||
foreach ($relation as $relationItem) {
|
||||
$data[$relationName][] = self::convertToArray($relationItem, ['ignore_getters' => true]);
|
||||
}
|
||||
} else {
|
||||
$data[$relationName] = self::convertToArray($relation, ['ignore_getters' => true]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
$row = is_object($row) && method_exists($row, 'makeHidden') ? $row->makeHidden(Arr::get($filters, 'hidden',
|
||||
[])) : $row;
|
||||
$row = is_object($row) && method_exists($row, 'makeVisible') ? $row->makeVisible(Arr::get($filters, 'visible',
|
||||
[])) : $row;
|
||||
|
||||
$data = $row instanceof Arrayable ? $row->toArray() : (array) $row;
|
||||
foreach ($data as &$value) {
|
||||
if ((is_object($value) && ! $value instanceof DateTime) || is_array($value)) {
|
||||
$value = self::convertToArray($value);
|
||||
}
|
||||
|
||||
unset($value);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public static function transform(array $data): array
|
||||
{
|
||||
return array_map(fn ($row) => self::transformRow($row), $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform row data into an array.
|
||||
*
|
||||
* @param array $row
|
||||
*/
|
||||
protected static function transformRow($row): array
|
||||
{
|
||||
foreach ($row as $key => $value) {
|
||||
if ($value instanceof DateTime) {
|
||||
$row[$key] = $value->format('Y-m-d H:i:s');
|
||||
} else {
|
||||
if (is_object($value) && method_exists($value, '__toString')) {
|
||||
$row[$key] = $value->__toString();
|
||||
} else {
|
||||
$row[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build parameters depending on # of arguments passed.
|
||||
*/
|
||||
public static function buildParameters(array $args): array
|
||||
{
|
||||
$parameters = [];
|
||||
|
||||
if (count($args) > 2) {
|
||||
$parameters[] = $args[0];
|
||||
foreach ($args[1] as $param) {
|
||||
$parameters[] = $param;
|
||||
}
|
||||
} else {
|
||||
foreach ($args[0] as $param) {
|
||||
$parameters[] = $param;
|
||||
}
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace all pattern occurrences with keyword.
|
||||
*/
|
||||
public static function replacePatternWithKeyword(array $subject, string $keyword, string $pattern = '$1'): array
|
||||
{
|
||||
$parameters = [];
|
||||
foreach ($subject as $param) {
|
||||
if (is_array($param)) {
|
||||
$parameters[] = self::replacePatternWithKeyword($param, $keyword, $pattern);
|
||||
} else {
|
||||
$parameters[] = str_replace($pattern, $keyword, (string) $param);
|
||||
}
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get column name from string.
|
||||
*/
|
||||
public static function extractColumnName(string $str, bool $wantsAlias): string
|
||||
{
|
||||
$matches = explode(' as ', Str::lower($str));
|
||||
|
||||
if (count($matches) > 1) {
|
||||
if ($wantsAlias) {
|
||||
return array_pop($matches);
|
||||
}
|
||||
|
||||
return array_shift($matches);
|
||||
} elseif (strpos($str, '.')) {
|
||||
$array = explode('.', $str);
|
||||
|
||||
return array_pop($array);
|
||||
}
|
||||
|
||||
return $str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds % wildcards to the given string.
|
||||
*/
|
||||
public static function wildcardLikeString(string $str, bool $lowercase = true): string
|
||||
{
|
||||
return static::wildcardString($str, '%', $lowercase);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds wildcards to the given string.
|
||||
*/
|
||||
public static function wildcardString(string $str, string $wildcard, bool $lowercase = true): string
|
||||
{
|
||||
$wild = $wildcard;
|
||||
$chars = (array) preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
|
||||
|
||||
if (count($chars) > 0) {
|
||||
foreach ($chars as $char) {
|
||||
$wild .= $char.$wildcard;
|
||||
}
|
||||
}
|
||||
|
||||
if ($lowercase) {
|
||||
$wild = Str::lower($wild);
|
||||
}
|
||||
|
||||
return $wild;
|
||||
}
|
||||
|
||||
public static function toJsonScript(array $parameters, int $options = 0): string
|
||||
{
|
||||
$values = [];
|
||||
$replacements = [];
|
||||
|
||||
foreach (Arr::dot($parameters) as $key => $value) {
|
||||
if (self::isJavascript($value, $key)) {
|
||||
$values[] = trim((string) $value);
|
||||
Arr::set($parameters, $key, '%'.$key.'%');
|
||||
$replacements[] = '"%'.$key.'%"';
|
||||
}
|
||||
}
|
||||
|
||||
$new = [];
|
||||
foreach ($parameters as $key => $value) {
|
||||
Arr::set($new, $key, $value);
|
||||
}
|
||||
|
||||
$json = (string) json_encode($new, $options);
|
||||
|
||||
return str_replace($replacements, $values, $json);
|
||||
}
|
||||
|
||||
public static function isJavascript(string|array|object|null $value, string $key): bool
|
||||
{
|
||||
if (empty($value) || is_array($value) || is_object($value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$callbacks = Config::get('datatables.callback', ['$', '$.', 'function']);
|
||||
|
||||
if (Str::startsWith($key, 'language.')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Str::startsWith(trim($value), $callbacks) || Str::contains($key, ['editor', 'minDate', 'maxDate']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
namespace Yajra\DataTables\Utilities;
|
||||
|
||||
use Illuminate\Http\Request as BaseRequest;
|
||||
|
||||
/**
|
||||
* @mixin \Illuminate\Http\Request
|
||||
*/
|
||||
class Request
|
||||
{
|
||||
/**
|
||||
* Proxy non-existing method calls to base request class.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
* @return mixed
|
||||
*/
|
||||
public function __call($name, $arguments)
|
||||
{
|
||||
$callback = [request(), $name];
|
||||
if (is_callable($callback)) {
|
||||
return call_user_func_array($callback, $arguments);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if an attribute exists on the base request.
|
||||
*
|
||||
* @param string $name
|
||||
*/
|
||||
public function __isset($name): bool
|
||||
{
|
||||
return isset(request()->$name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get attributes from request instance.
|
||||
*
|
||||
* @param string $name
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
return request()->__get($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all columns request input.
|
||||
*/
|
||||
public function columns(): array
|
||||
{
|
||||
return (array) request()->input('columns');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if DataTables is searchable.
|
||||
*/
|
||||
public function isSearchable(): bool
|
||||
{
|
||||
return request()->input('search.value') != '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if DataTables must uses regular expressions.
|
||||
*/
|
||||
public function isRegex(int $index): bool
|
||||
{
|
||||
return request()->input("columns.$index.search.regex") === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get orderable columns.
|
||||
*/
|
||||
public function orderableColumns(): array
|
||||
{
|
||||
if (! $this->isOrderable()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$orderable = [];
|
||||
for ($i = 0, $c = count((array) request()->input('order')); $i < $c; $i++) {
|
||||
/** @var int $order_col */
|
||||
$order_col = request()->input("order.$i.column");
|
||||
|
||||
/** @var string $direction */
|
||||
$direction = request()->input("order.$i.dir");
|
||||
|
||||
$order_dir = $direction && strtolower($direction) === 'asc' ? 'asc' : 'desc';
|
||||
if ($this->isColumnOrderable($order_col)) {
|
||||
$orderable[] = ['column' => $order_col, 'direction' => $order_dir];
|
||||
}
|
||||
}
|
||||
|
||||
return $orderable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if DataTables ordering is enabled.
|
||||
*/
|
||||
public function isOrderable(): bool
|
||||
{
|
||||
return request()->input('order') && count((array) request()->input('order')) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a column is orderable.
|
||||
*/
|
||||
public function isColumnOrderable(int $index): bool
|
||||
{
|
||||
return request()->input("columns.$index.orderable", 'true') == 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get searchable column indexes.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function searchableColumnIndex()
|
||||
{
|
||||
$searchable = [];
|
||||
$columns = (array) request()->input('columns');
|
||||
for ($i = 0, $c = count($columns); $i < $c; $i++) {
|
||||
if ($this->isColumnSearchable($i, false)) {
|
||||
$searchable[] = $i;
|
||||
}
|
||||
}
|
||||
|
||||
return $searchable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a column is searchable.
|
||||
*/
|
||||
public function isColumnSearchable(int $i, bool $column_search = true): bool
|
||||
{
|
||||
if ($column_search) {
|
||||
return
|
||||
(
|
||||
request()->input("columns.$i.searchable", 'true') === 'true'
|
||||
||
|
||||
request()->input("columns.$i.searchable", 'true') === true
|
||||
)
|
||||
&& $this->columnKeyword($i) != '';
|
||||
}
|
||||
|
||||
return
|
||||
request()->input("columns.$i.searchable", 'true') === 'true'
|
||||
||
|
||||
request()->input("columns.$i.searchable", 'true') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get column's search value.
|
||||
*/
|
||||
public function columnKeyword(int $index): string
|
||||
{
|
||||
/** @var string $keyword */
|
||||
$keyword = request()->input("columns.$index.search.value") ?? '';
|
||||
|
||||
return $this->prepareKeyword($keyword);
|
||||
}
|
||||
|
||||
public function columnControl(int $index): array
|
||||
{
|
||||
return request()->array("columns.$index.columnControl");
|
||||
}
|
||||
|
||||
public function columnControlSearch(int $index): array
|
||||
{
|
||||
return request()->array("columns.$index.columnControl.search");
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare keyword string value.
|
||||
*/
|
||||
protected function prepareKeyword(float|array|int|string $keyword): string
|
||||
{
|
||||
if (is_array($keyword)) {
|
||||
return implode(' ', $keyword);
|
||||
}
|
||||
|
||||
return (string) $keyword;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get global search keyword.
|
||||
*/
|
||||
public function keyword(): string
|
||||
{
|
||||
/** @var string $keyword */
|
||||
$keyword = request()->input('search.value') ?? '';
|
||||
|
||||
return $this->prepareKeyword($keyword);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get column name by index.
|
||||
*/
|
||||
public function columnName(int $i): ?string
|
||||
{
|
||||
/** @var string[] $column */
|
||||
$column = request()->input("columns.$i");
|
||||
|
||||
return (isset($column['name']) && $column['name'] != '') ? $column['name'] : $column['data'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if DataTables allow pagination.
|
||||
*/
|
||||
public function isPaginationable(): bool
|
||||
{
|
||||
return ! is_null(request()->input('start')) &&
|
||||
! is_null(request()->input('length')) &&
|
||||
request()->input('length') != -1;
|
||||
}
|
||||
|
||||
public function getBaseRequest(): BaseRequest
|
||||
{
|
||||
return request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get starting record value.
|
||||
*/
|
||||
public function start(): int
|
||||
{
|
||||
$start = request()->input('start', 0);
|
||||
|
||||
return is_numeric($start) ? intval($start) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get per page length.
|
||||
*/
|
||||
public function length(): int
|
||||
{
|
||||
$length = request()->input('length', 10);
|
||||
|
||||
return is_numeric($length) ? intval($length) : 10;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get draw request.
|
||||
*/
|
||||
public function draw(): int
|
||||
{
|
||||
$draw = request()->input('draw', 0);
|
||||
|
||||
return is_numeric($draw) ? intval($draw) : 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
/*
|
||||
* DataTables search options.
|
||||
*/
|
||||
'search' => [
|
||||
/*
|
||||
* Smart search will enclose search keyword with wildcard string "%keyword%".
|
||||
* SQL: column LIKE "%keyword%"
|
||||
*/
|
||||
'smart' => true,
|
||||
|
||||
/*
|
||||
* Multi-term search will explode search keyword using spaces resulting into multiple term search.
|
||||
*/
|
||||
'multi_term' => true,
|
||||
|
||||
/*
|
||||
* Case insensitive will search the keyword in lower case format.
|
||||
* SQL: LOWER(column) LIKE LOWER(keyword)
|
||||
*/
|
||||
'case_insensitive' => true,
|
||||
|
||||
/*
|
||||
* Wild card will add "%" in between every characters of the keyword.
|
||||
* SQL: column LIKE "%k%e%y%w%o%r%d%"
|
||||
*/
|
||||
'use_wildcards' => false,
|
||||
|
||||
/*
|
||||
* Perform a search which starts with the given keyword.
|
||||
* SQL: column LIKE "keyword%"
|
||||
*/
|
||||
'starts_with' => false,
|
||||
],
|
||||
|
||||
/*
|
||||
* DataTables internal index id response column name.
|
||||
*/
|
||||
'index_column' => 'DT_RowIndex',
|
||||
|
||||
/*
|
||||
* List of available builders for DataTables.
|
||||
* This is where you can register your custom DataTables builder.
|
||||
*/
|
||||
'engines' => [
|
||||
'eloquent' => Yajra\DataTables\EloquentDataTable::class,
|
||||
'query' => Yajra\DataTables\QueryDataTable::class,
|
||||
'collection' => Yajra\DataTables\CollectionDataTable::class,
|
||||
'paginator' => Yajra\DataTables\PaginatorDataTable::class,
|
||||
'resource' => Yajra\DataTables\ApiResourceDataTable::class,
|
||||
],
|
||||
|
||||
/*
|
||||
* DataTables accepted builder to engine mapping.
|
||||
* This is where you can override which engine a builder should use
|
||||
* Note, only change this if you know what you are doing!
|
||||
*/
|
||||
'builders' => [
|
||||
// Illuminate\Database\Eloquent\Relations\Relation::class => 'eloquent',
|
||||
// Illuminate\Database\Eloquent\Builder::class => 'eloquent',
|
||||
// Illuminate\Database\Query\Builder::class => 'query',
|
||||
// Illuminate\Support\Collection::class => 'collection',
|
||||
// Illuminate\Pagination\LengthAwarePaginator::class => 'paginator',
|
||||
],
|
||||
|
||||
/*
|
||||
* Nulls last sql pattern for PostgreSQL & Oracle.
|
||||
* For MySQL, use 'CASE WHEN :column IS NULL THEN 1 ELSE 0 END, :column :direction'
|
||||
*/
|
||||
'nulls_last_sql' => ':column :direction NULLS LAST',
|
||||
|
||||
/*
|
||||
* User friendly message to be displayed on user if error occurs.
|
||||
* Possible values:
|
||||
* null - The exception message will be used on error response.
|
||||
* 'throw' - Throws a \Yajra\DataTables\Exceptions\Exception. Use your custom error handler if needed.
|
||||
* 'custom message' - Any friendly message to be displayed to the user. You can also use translation key.
|
||||
*/
|
||||
'error' => env('DATATABLES_ERROR', null),
|
||||
|
||||
/*
|
||||
* Default columns definition of DataTable utility functions.
|
||||
*/
|
||||
'columns' => [
|
||||
/*
|
||||
* List of columns hidden/removed on json response.
|
||||
*/
|
||||
'excess' => ['rn', 'row_num'],
|
||||
|
||||
/*
|
||||
* List of columns to be escaped. If set to *, all columns are escape.
|
||||
* Note: You can set the value to empty array to disable XSS protection.
|
||||
*/
|
||||
'escape' => '*',
|
||||
|
||||
/*
|
||||
* List of columns that are allowed to display html content.
|
||||
* Note: Adding columns to list will make us available to XSS attacks.
|
||||
*/
|
||||
'raw' => ['action'],
|
||||
|
||||
/*
|
||||
* List of columns are forbidden from being searched/sorted.
|
||||
*/
|
||||
'blacklist' => ['password', 'remember_token'],
|
||||
|
||||
/*
|
||||
* List of columns that are only allowed for search/sort.
|
||||
* If set to *, all columns are allowed.
|
||||
*/
|
||||
'whitelist' => '*',
|
||||
],
|
||||
|
||||
/*
|
||||
* JsonResponse header and options config.
|
||||
*/
|
||||
'json' => [
|
||||
'header' => [],
|
||||
'options' => 0,
|
||||
],
|
||||
|
||||
/*
|
||||
* Default condition to determine if a parameter is a callback or not.
|
||||
* Callbacks needs to start by those terms, or they will be cast to string.
|
||||
*/
|
||||
'callback' => ['$', '$.', 'function'],
|
||||
];
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
if (! function_exists('datatables')) {
|
||||
/**
|
||||
* Helper to make a new DataTable instance from source.
|
||||
* Or return the factory if source is not set.
|
||||
*
|
||||
* @param \Illuminate\Contracts\Database\Query\Builder|\Illuminate\Contracts\Database\Eloquent\Builder|\Illuminate\Support\Collection|array|null $source
|
||||
* @return ($source is null ? \Yajra\DataTables\DataTables : \Yajra\DataTables\DataTableAbstract)
|
||||
*
|
||||
* @throws \Yajra\DataTables\Exceptions\Exception
|
||||
*/
|
||||
function datatables($source = null)
|
||||
{
|
||||
/** @var Yajra\DataTables\DataTables $dataTable */
|
||||
$dataTable = app('datatables');
|
||||
|
||||
if (is_null($source)) {
|
||||
return $dataTable;
|
||||
}
|
||||
|
||||
return $dataTable->make($source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
if (! function_exists('config_path')) {
|
||||
/**
|
||||
* Get the configuration path.
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
function config_path($path = '')
|
||||
{
|
||||
return app()->basePath().'/config'.($path ? '/'.$path : $path);
|
||||
}
|
||||
}
|
||||
|
||||
if (! function_exists('public_path')) {
|
||||
/**
|
||||
* Return the path to public dir.
|
||||
*
|
||||
* @param null $path
|
||||
* @return string
|
||||
*/
|
||||
function public_path($path = null)
|
||||
{
|
||||
return rtrim((string) app()->basePath('public/'.$path), '/');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user