94 lines
3.0 KiB
PHP
94 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace Itguild\EloquentTable;
|
|
|
|
use Exception;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\App;
|
|
use itguild\forms\debug\Debug;
|
|
|
|
class EloquentDataProvider
|
|
{
|
|
protected int $totalCount;
|
|
|
|
protected int $perPage = 10;
|
|
|
|
protected int $currentPage = 1;
|
|
|
|
protected Model $model;
|
|
|
|
protected $queryBuilder = false;
|
|
|
|
protected array $options = [];
|
|
protected array $meta = [];
|
|
protected array $filters = [];
|
|
protected string $jsonStr = '';
|
|
|
|
/**
|
|
* @throws Exception
|
|
*/
|
|
public function __construct($source, array $options)
|
|
{
|
|
if (is_string($source)) {
|
|
$this->queryBuilder = $source::query();
|
|
$model = new $source();
|
|
} elseif (is_object($source)) {
|
|
$this->queryBuilder = $source;
|
|
$model = $source->getModel();
|
|
} else {
|
|
throw new Exception(message: "source is not valid");
|
|
}
|
|
$this->options = $options;
|
|
$this->currentPage = $this->options['currentPage'] ?? 1;
|
|
$this->perPage = $this->options['perPage'] ?? 10;
|
|
$this->meta['total'] = $model->count();
|
|
$this->meta['totalWithFilters'] = $this->queryBuilder->count();
|
|
$this->meta['columns'] = $options['columns'] ?? $model->labels();
|
|
$this->meta['perPage'] = $options['perPage'] ?? 10;
|
|
$this->meta['currentPage'] = $options['currentPage'] ?? 1;
|
|
$this->meta['baseUrl'] = $options['baseUrl'] ?? $model->table;
|
|
$this->meta['params'] = $options['params'] ?? [];
|
|
$this->meta['actions'] = $options['actions'] ?? [];
|
|
$this->meta['searchPrefix'] = $options['searchPrefix'] ?? '/search';
|
|
$this->meta['searchParams'] = $options['searchParams'] ?? [];
|
|
$this->meta['showFiltersRow'] = $options['showFiltersRow'] ?? true;
|
|
$this->filters = $options['filters'] ?? [];
|
|
$this->createQuery();
|
|
$this->jsonStr = (new JSONCreator($this->meta, $this->getCollection()->toArray(), $this->filters,))->getJson();
|
|
}
|
|
|
|
public function createQuery(): void
|
|
{
|
|
if ($this->meta['searchParams']){
|
|
foreach ($this->meta['searchParams'] as $name => $param){
|
|
if (array_key_exists($name, $this->meta['columns']) && !empty($param)){
|
|
if (is_numeric($param)){
|
|
$this->queryBuilder->where($name, $this->meta['searchParams'][$name]);
|
|
}
|
|
elseif (is_string($param)){
|
|
$this->queryBuilder->where($name,'like', '%' . $param. '%');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if ($this->currentPage > 1) {
|
|
$this->queryBuilder->skip(($this->currentPage - 1) * $this->perPage)->take($this->perPage);
|
|
} else {
|
|
$this->queryBuilder->take($this->perPage);
|
|
}
|
|
}
|
|
|
|
public function getCollection()
|
|
{
|
|
return $this->queryBuilder->get();
|
|
}
|
|
|
|
/**
|
|
* @return string|null
|
|
*/
|
|
public function getJson(): string|null
|
|
{
|
|
return $this->jsonStr;
|
|
}
|
|
|
|
} |