1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ElfSundae\Laravel\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
|
3 |
|
public function make($source) |
20
|
|
|
{ |
21
|
3 |
|
if (is_array($source)) { |
22
|
1 |
|
$source = new Collection($source); |
23
|
|
|
} |
24
|
|
|
|
25
|
3 |
|
if ($engine = $this->getEngineForSource($source)) { |
26
|
3 |
|
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
|
3 |
|
protected function getEngineForSource($source) |
39
|
|
|
{ |
40
|
3 |
|
$result = null; |
41
|
|
|
|
42
|
3 |
|
foreach (config('datatables.builders') as $type => $engine) { |
43
|
3 |
|
if ($source instanceof $type) { |
44
|
3 |
|
if (! isset($tmpType) || is_subclass_of($type, $tmpType)) { |
45
|
3 |
|
$tmpType = $type; |
46
|
3 |
|
$result = $engine; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
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
|
3 |
|
protected function createDataTable($engine, $source) |
63
|
|
|
{ |
64
|
3 |
|
if ($class = class_exists($engine) ? $engine : Arr::get(config('datatables.engines'), $engine)) { |
65
|
3 |
|
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
|
1 |
|
public function __call($method, $parameters) |
79
|
|
|
{ |
80
|
1 |
|
return $this->createDataTable(Str::snake($method), ...$parameters); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|