Completed
Push — master ( 21470b...961dbd )
by Elf
06:51
created

DataTables   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 90%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 3
dl 0
loc 73
ccs 18
cts 20
cp 0.9
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A make() 0 12 3
B getEngineForSource() 0 15 5
A createDataTable() 0 8 3
A __call() 0 4 1
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 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