Completed
Push — master ( 74da27...ac625a )
by wen
12:26
created

ModelConfig::compileWhere()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 2
nop 0
1
<?php
2
3
namespace Sco\Admin\Config;
4
5
use JsonSerializable;
6
use Illuminate\Contracts\Support\Arrayable;
7
use Illuminate\Contracts\Support\Jsonable;
8
use Sco\Admin\Exceptions\InvalidArgumentException;
9
use Sco\Admin\Contracts\Config as ConfigContract;
10
11
class ModelConfig extends Config implements ConfigContract, Arrayable, Jsonable, JsonSerializable
0 ignored issues
show
Bug introduced by
There is at least one abstract method in this class. Maybe declare it as abstract, or implement the remaining methods: jsonSerialize, toArray, toJson
Loading history...
12
{
13
14
    protected $orderBy = [];
15
    protected $wheres = [];
16
17
    /**
18
     * Get Model
19
     *
20
     * @return \Illuminate\Database\Eloquent\Model
21
     * @throws \Sco\Admin\Exceptions\InvalidArgumentException
22
     */
23
    protected function getModel()
24
    {
25
        $modelName = $this->getOriginal('model');
26
        if (class_exists($modelName)) {
27
            return new $modelName();
28
        }
29
        throw new InvalidArgumentException("class {$modelName} not found");
30
    }
31
32
    public function where($filters)
33
    {
34
        $this->wheres = $filters;
35
        return $this;
36
    }
37
38
    public function orderBy($column, $direction = 'asc')
39
    {
40
        $this->orderBy = compact('column', 'direction');
41
        return $this;
42
    }
43
44
    public function paginate($perPage = null)
45
    {
46
        $model = $this->compileWhere();
47
        if (!empty($this->orderBy)) {
48
            $model->orderBy($this->orderBy['column'], $this->orderBy['direction']);
49
        }
50
51
        $data = $model->paginate($perPage);
52
        return $data;
53
    }
54
55
    protected function compileWhere()
56
    {
57
        $model = $this->getModel();
58
        if (!empty($this->wheres)) {
59
            foreach ($this->wheres as $key => $where) {
60
                list($operator, $value) = is_array($where) ? $where : ['=', $where];
61
                $model->where($key, $operator, $value);
62
            }
63
        }
64
        return $model;
65
    }
66
}
67