Completed
Push — master ( 7bd89e...eb66c2 )
by Sergey
06:14
created

Model   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 224
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 90.54%

Importance

Changes 28
Bugs 6 Features 2
Metric Value
wmc 25
c 28
b 6
f 2
lcom 1
cbo 11
dl 0
loc 224
ccs 67
cts 74
cp 0.9054
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A toArray() 0 6 1
A jsonSerialize() 0 4 1
A delete() 0 19 3
A createInstance() 0 4 1
B find() 0 33 4
A findOrNew() 0 9 2
A findOrFail() 0 8 2
A create() 0 14 2
A destroy() 0 10 4
B save() 0 22 4
1
<?php
2
3
namespace Isswp101\Persimmon;
4
5
use Elasticsearch\Common\Exceptions\Missing404Exception;
6
use Exception;
7
use Isswp101\Persimmon\Contracts\Arrayable;
8
use Isswp101\Persimmon\Contracts\Jsonable;
9
use Isswp101\Persimmon\Contracts\Stringable;
10
use Isswp101\Persimmon\DAL\IDAL;
11
use Isswp101\Persimmon\Exceptions\ModelNotFoundException;
12
use Isswp101\Persimmon\Traits\Cacheable;
13
use Isswp101\Persimmon\Traits\Eventable;
14
use Isswp101\Persimmon\Traits\Fillable;
15
use Isswp101\Persimmon\Traits\Idable;
16
use Isswp101\Persimmon\Traits\Mergeable;
17
use Isswp101\Persimmon\Traits\Presentable;
18
use Isswp101\Persimmon\Traits\Timestampable;
19
use Isswp101\Persimmon\Traits\Userable;
20
use JsonSerializable;
21
use LogicException;
22
23
abstract class Model implements Arrayable, Jsonable, Stringable, JsonSerializable
24
{
25
    use Presentable, Eventable, Mergeable;
26
    use Idable, Userable, Timestampable;
27
    use Fillable, Cacheable;
28
29
    /**
30
     * @var IDAL
31
     */
32
    public $_dal;
33
34
    /**
35
     * @var bool
36
     */
37
    public $_exist = false;
38
39
    /**
40
     * Create a new instance.
41
     *
42
     * @param IDAL $dal
43
     * @param array $attributes
44
     */
45 52
    public function __construct(IDAL $dal, array $attributes = [])
46
    {
47 52
        $this->_dal = $dal;
48
49 52
        $this->fill($attributes);
50 52
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function toArray()
56
    {
57 28
        return array_where(get_object_vars($this), function ($key) {
58 28
            return !starts_with($key, '_');
59 28
        });
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function jsonSerialize()
66
    {
67
        return $this->toArray();
68
    }
69
70
    /**
71
     * Save the model.
72
     *
73
     * @param array $columns
74
     * @return bool
75
     */
76 24
    public function save($columns = ['*'])
77
    {
78 24
        $columns = $columns ? (array)$columns : ['*'];
79
80 24
        if ($this->saving() === false) {
81
            return false;
82
        }
83
84 24
        $this->fillTimestamp();
85
86 24
        $this->_dal->put($columns);
87
88 24
        $this->_exist = true;
89
90
        // self::cache()->put($id, $this);
91
92 24
        if ($this->saved() === false) {
93
            return false;
94
        }
95
96 24
        return true;
97
    }
98
99
    /**
100
     * Delete the model.
101
     *
102
     * @return bool
103
     */
104 6
    public function delete()
105
    {
106 6
        if ($this->deleting() === false) {
107 2
            return false;
108
        }
109
110 6
        $this->_dal->delete();
111
112 6
        $this->_exist = false;
113
114 6
        $cache = self::cache();
115 6
        $cache->forget($this->getId());
116
117 6
        if ($this->deleted() === false) {
118
            return false;
119
        }
120
121 6
        return true;
122
    }
123
124
    /**
125
     * Create a new instance.
126
     *
127
     * @return static
128
     */
129
    public static function createInstance()
130
    {
131
        throw new LogicException('Static method `createInstance()` must be overridden and return `new static(args)`');
132
    }
133
134
    /**
135
     * Find a model by its primary key.
136
     *
137
     * @param mixed $id
138
     * @param array $columns
139
     * @param array $options
140
     * @return static
141
     */
142 22
    public static function find($id, array $columns = ['*'], $options = [])
143
    {
144
        // Return a cached instance if one exists
145 22
        $cache = self::cache();
146 22
        if ($cache->containsAttributes($id, $columns)) {
147 10
            return $cache->get($id);
148
        }
149
150
        // Return attributes which are not cached
151 14
        $columns = $cache->getNotCachedAttributes($id, $columns);
152
153
        // Create a new model
154 14
        $model = static::createInstance();
155 14
        $model->setId($id);
156
157
        // Merge options
158 14
        $options = array_merge($options, ['columns' => $columns == ['*'] ? [] : $columns]);
159
160
        // Get by id
161
        try {
162 14
            $model->_dal->get($id, $options);
163 14
        } catch (Missing404Exception $e) {
164 4
            return null;
165
        }
166
167
        // Fill internal attributes
168 10
        $model->_exist = true;
169
170
        // Put model to cache
171 10
        $model = $cache->put($id, $model, $columns);
172
173 10
        return $model;
174
    }
175
176
    /**
177
     * Find a model by its primary key or return new model.
178
     *
179
     * @param mixed $id
180
     * @return static
181
     */
182 2
    public static function findOrNew($id)
183
    {
184 2
        $model = static::find($id);
185 2
        if (is_null($model)) {
186 2
            $model = static::createInstance();
187 2
            $model->setId($id);
188 2
        }
189 2
        return $model;
190
    }
191
192
    /**
193
     * Find a model by its primary key or throw an exception.
194
     *
195
     * @param mixed $id
196
     * @param array $columns
197
     * @param int $parent
198
     * @return static
199
     */
200 4
    public static function findOrFail($id, array $columns = ['*'], $parent = null)
201
    {
202 4
        $model = static::find($id, $columns, ['parent' => $parent]);
203 4
        if (is_null($model)) {
204 2
            throw new ModelNotFoundException(get_called_class(), $id);
205
        }
206 2
        return $model;
207
    }
208
209
    /**
210
     * Save a new model and return the instance.
211
     *
212
     * @param array $attributes
213
     * @throws Exception
214
     * @return static
215
     */
216 8
    public static function create(array $attributes = [])
217
    {
218 8
        $model = static::createInstance();
219
220 8
        if (array_key_exists('id', $attributes)) {
221 8
            $model->setId($attributes['id']);
222 8
        }
223
224 8
        $model->fill($attributes);
225
226 8
        $model->save();
227
228 8
        return $model;
229
    }
230
231
    /**
232
     * Destroy the models by the given id.
233
     *
234
     * @param mixed $id
235
     */
236 2
    public static function destroy($id)
237
    {
238 2
        $ids = is_array($id) ? $id : [$id];
239 2
        foreach ($ids as $id) {
240 2
            $model = static::find($id);
241 2
            if (!is_null($model)) {
242 2
                $model->delete();
243 2
            }
244 2
        }
245 2
    }
246
}
247