Completed
Push — master ( 1aac38...816340 )
by Sergey
23s
created

Model::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
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
22
abstract class Model implements Arrayable, Jsonable, Stringable, JsonSerializable
23
{
24
    use Presentable, Eventable, Mergeable;
25
    use Idable, Userable, Timestampable;
26
    use Fillable, Cacheable;
27
28
    /**
29
     * @var IDAL
30
     */
31
    public $_dal;
32
33
    /**
34
     * @var bool
35
     */
36
    public $_exist = false;
37
38
    /**
39
     * Create a new instance.
40
     *
41
     * @param IDAL $dal
42
     * @param array $attributes
43
     */
44 52
    public function __construct(IDAL $dal, array $attributes = [])
45
    {
46 52
        $this->_dal = $dal;
47
48 52
        $this->fill($attributes);
49 52
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function toArray()
55
    {
56 28
        return array_where(get_object_vars($this), function ($key) {
57 28
            return !starts_with($key, '_');
58 28
        });
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function jsonSerialize()
65
    {
66
        return $this->toArray();
67
    }
68
69
    /**
70
     * Save the model.
71
     *
72
     * @param array $columns
73
     * @return bool
74
     */
75 24
    public function save($columns = ['*'])
76
    {
77 24
        $columns = $columns ? (array)$columns : ['*'];
78
79 24
        if ($this->saving() === false) {
80
            return false;
81
        }
82
83 24
        $this->fillTimestamp();
84
85 24
        $this->_dal->put($columns);
86
87 24
        $this->_exist = true;
88
89
        // self::cache()->put($id, $this);
90
91 24
        if ($this->saved() === false) {
92
            return false;
93
        }
94
95 24
        return true;
96
    }
97
98
    /**
99
     * Delete the model.
100
     *
101
     * @return bool
102
     */
103 6
    public function delete()
104
    {
105 6
        if ($this->deleting() === false) {
106 2
            return false;
107
        }
108
109 6
        $this->_dal->delete();
110
111 6
        $this->_exist = false;
112
113 6
        $cache = self::cache();
114 6
        $cache->forget($this->getId());
115
116 6
        if ($this->deleted() === false) {
117
            return false;
118
        }
119
120 6
        return true;
121
    }
122
123
    /**
124
     * @return static
125
     */
126 38
    final public static function createInstance()
127
    {
128 38
        return new static();
0 ignored issues
show
Bug introduced by
The call to Model::__construct() misses a required argument $dal.

This check looks for function calls that miss required arguments.

Loading history...
129
    }
130
131
    /**
132
     * Find a model by its primary key.
133
     *
134
     * @param mixed $id
135
     * @param array $columns
136
     * @param array $options
137
     * @return static
138
     */
139 22
    public static function find($id, array $columns = ['*'], $options = [])
140
    {
141
        // Return a cached instance if one exists
142 22
        $cache = self::cache();
143 22
        if ($cache->containsAttributes($id, $columns)) {
144 10
            return $cache->get($id);
145
        }
146
147
        // Return attributes which are not cached
148 14
        $columns = $cache->getNotCachedAttributes($id, $columns);
149
150
        // Create a new model
151 14
        $model = static::createInstance();
152 14
        $model->setId($id);
153
154
        // Merge options
155 14
        $options = array_merge($options, ['columns' => $columns == ['*'] ? [] : $columns]);
156
157
        // Get by id
158
        try {
159 14
            $model->_dal->get($id, $options);
160 14
        } catch (Missing404Exception $e) {
161 4
            return null;
162
        }
163
164
        // Fill internal attributes
165 10
        $model->_exist = true;
166
167
        // Put model to cache
168 10
        $model = $cache->put($id, $model, $columns);
169
170 10
        return $model;
171
    }
172
173
    /**
174
     * Find a model by its primary key or return new model.
175
     *
176
     * @param mixed $id
177
     * @return static
178
     */
179 2
    public static function findOrNew($id)
180
    {
181 2
        $model = static::find($id);
182 2
        if (is_null($model)) {
183 2
            $model = static::createInstance();
184 2
            $model->setId($id);
185 2
        }
186 2
        return $model;
187
    }
188
189
    /**
190
     * Find a model by its primary key or throw an exception.
191
     *
192
     * @param mixed $id
193
     * @param array $columns
194
     * @param int $parent
195
     * @return static
196
     */
197 4
    public static function findOrFail($id, array $columns = ['*'], $parent = null)
198
    {
199 4
        $model = static::find($id, $columns, ['parent' => $parent]);
200 4
        if (is_null($model)) {
201 2
            throw new ModelNotFoundException(get_called_class(), $id);
202
        }
203 2
        return $model;
204
    }
205
206
    /**
207
     * Save a new model and return the instance.
208
     *
209
     * @param array $attributes
210
     * @throws Exception
211
     * @return static
212
     */
213 8
    public static function create(array $attributes = [])
214
    {
215 8
        $model = static::createInstance();
216
217 8
        if (array_key_exists('id', $attributes)) {
218 8
            $model->setId($attributes['id']);
219 8
        }
220
221 8
        $model->fill($attributes);
222
223 8
        $model->save();
224
225 8
        return $model;
226
    }
227
228
    /**
229
     * Destroy the models by the given id.
230
     *
231
     * @param mixed $id
232
     */
233 2
    public static function destroy($id)
234
    {
235 2
        $ids = is_array($id) ? $id : [$id];
236 2
        foreach ($ids as $id) {
237 2
            $model = static::find($id);
238 2
            if (!is_null($model)) {
239 2
                $model->delete();
240 2
            }
241 2
        }
242 2
    }
243
}
244