CrudServiceBase::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 2
1
<?php
2
3
namespace IanOlson\Support\Services;
4
5
use Illuminate\Support\Facades\Lang;
6
use IanOlson\Support\Traits\ServiceTrait;
7
use IanOlson\Support\Traits\UpdateTrait;
8
use IanOlson\Support\Traits\ValidateTrait;
9
10
abstract class CrudServiceBase
11
{
12
    use ServiceTrait;
13
    use UpdateTrait;
14
    use ValidateTrait;
15
16
    /**
17
     * Construct.
18
     *
19
     * @param null $model
20
     */
21 2
    public function __construct($model = null)
22
    {
23 2
        if (isset($model)) {
24 2
            $this->setModel($model);
25 1
        }
26 2
    }
27
28
    /**
29
     * {@inheritDoc}
30
     */
31 4
    public function index()
32
    {
33 4
        return $this->createModel()->newQuery()->get();
34
    }
35
36
    /**
37
     * {@inheritDoc}
38
     */
39 2
    public function create(array $data = [])
40
    {
41 2
        $this->validate($data);
42
43
        $model = $this->createModel();
44
45
        $this->updateAttributes($model, $data);
46
47 4
        $model->save();
48
49 4
        return $model;
50
    }
51 2
52
    /**
53 2
     * {@inheritDoc}
54
     */
55 2
    public function read($id)
56
    {
57 2
        return $this->createModel()->newQuery()->where('id', $id)->first();
58
    }
59
60
    /**
61
     * {@inheritDoc}
62
     */
63 6
    public function update($id, array $data = [])
64
    {
65 6
        if (!$model = $this->read($id)) {
66 2
            $this->throwException(Lang::get('support.exceptions.model.read'));
67
        }
68
69 4
        $this->validate($data);
70
71 2
        $this->updateAttributes($model, $data);
72
73 2
        $model->save();
74
75 2
        return $model;
76
    }
77
78
    /**
79
     * {@inheritDoc}
80
     */
81 4
    public function delete($id)
82
    {
83 4
        if (!$model = $this->read($id)) {
84 2
            $this->throwException(Lang::get('support.exceptions.model.read'));
85
        }
86
87 2
        $model->delete();
88
89 2
        return true;
90
    }
91
}
92