ElfSundae /
laravel-datatables
| 1 | <?php |
||
| 2 | |||
| 3 | namespace ElfSundae\DataTables; |
||
| 4 | |||
| 5 | use Exception; |
||
| 6 | use Illuminate\Support\Arr; |
||
| 7 | use Illuminate\Support\Str; |
||
| 8 | use Illuminate\Support\Collection; |
||
| 9 | |||
| 10 | class DataTables |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * Make a DataTable instance from source. |
||
| 14 | * |
||
| 15 | * @param mixed $source |
||
| 16 | * @return mixed |
||
| 17 | * @throws \Exception |
||
| 18 | */ |
||
| 19 | 6 | public function make($source) |
|
| 20 | { |
||
| 21 | 6 | if (is_array($source)) { |
|
| 22 | 2 | $source = new Collection($source); |
|
| 23 | } |
||
| 24 | |||
| 25 | 6 | if ($engine = $this->getEngineForSource($source)) { |
|
| 26 | 6 | return $this->createDataTable($engine, $source); |
|
| 27 | } |
||
| 28 | |||
| 29 | throw new Exception('No available engine for '.get_class($source)); |
||
| 30 | } |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Get the optimum engine for the given data source. |
||
| 34 | * |
||
| 35 | * @param mixed $source |
||
| 36 | * @return string|null |
||
| 37 | */ |
||
| 38 | 6 | protected function getEngineForSource($source) |
|
| 39 | { |
||
| 40 | 6 | $result = null; |
|
| 41 | |||
| 42 | 6 | foreach (config('datatables.builders') as $type => $engine) { |
|
| 43 | 6 | if ($source instanceof $type) { |
|
| 44 | 6 | if (! isset($tmpType) || is_subclass_of($type, $tmpType)) { |
|
| 45 | 6 | $tmpType = $type; |
|
| 46 | 6 | $result = $engine; |
|
| 47 | } |
||
| 48 | } |
||
| 49 | } |
||
| 50 | |||
| 51 | 6 | return $result; |
|
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Create a new DataTable instance. |
||
| 56 | * |
||
| 57 | * @param string $engine |
||
| 58 | * @param mixed $source |
||
| 59 | * @return mixed |
||
| 60 | * @throws \Exception |
||
| 61 | */ |
||
| 62 | 6 | protected function createDataTable($engine, $source) |
|
| 63 | { |
||
| 64 | 6 | if ($class = class_exists($engine) ? $engine : Arr::get(config('datatables.engines'), $engine)) { |
|
| 65 | 6 | return new $class($source); |
|
| 66 | } |
||
| 67 | |||
| 68 | throw new Exception("Unsupported DataTable engine [$engine]"); |
||
| 69 | } |
||
| 70 | |||
| 71 | /** |
||
| 72 | * Make a DataTable instance by using method name as engine. |
||
| 73 | * |
||
| 74 | * @param string $method |
||
| 75 | * @param array $parameters |
||
| 76 | * @return mixed |
||
| 77 | */ |
||
| 78 | 2 | public function __call($method, $parameters) |
|
| 79 | { |
||
| 80 | 2 | return $this->createDataTable(Str::snake($method), ...$parameters); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 81 | } |
||
| 82 | } |
||
| 83 |