Completed
Push — master ( 816340...ab4a72 )
by Sergey
05:20
created

Model::findOrNew()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3.4578

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 2
cts 7
cp 0.2857
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
crap 3.4578
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 14
    public function __construct(IDAL $dal, array $attributes = [])
45
    {
46 14
        $this->_dal = $dal;
47
48 14
        $this->fill($attributes);
49 14
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function toArray()
55
    {
56 14
        return array_where(get_object_vars($this), function ($key) {
57 14
            return !starts_with($key, '_');
58 14
        });
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 12
    public function save($columns = ['*'])
76
    {
77 12
        $columns = $columns ? (array)$columns : ['*'];
78
79 12
        if ($this->saving() === false) {
80
            return false;
81
        }
82
83 12
        $this->fillTimestamp();
84
85 12
        $this->_dal->put($columns);
86
87 12
        $this->_exist = true;
88
89
        // self::cache()->put($id, $this);
90
91 12
        if ($this->saved() === false) {
92
            return false;
93
        }
94
95 12
        return true;
96
    }
97
98
    /**
99
     * Delete the model.
100
     *
101
     * @return bool
102
     */
103 2
    public function delete()
104
    {
105 2
        if ($this->deleting() === false) {
106 2
            return false;
107
        }
108
109 2
        $this->_dal->delete();
110
111 1
        $this->_exist = false;
112
113 1
        $cache = self::cache();
114 1
        $cache->forget($this->getId());
115
116 1
        if ($this->deleted() === false) {
117
            return false;
118
        }
119
120 1
        return true;
121
    }
122
123
    /**
124
     * Create a new instance.
125
     *
126
     * @param array $attributes
127
     * @return static
128
     */
129 42
    public static function createInstance(array $attributes = [])
130
    {
131 42
        return new static(null, $attributes);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object<Isswp101\Persimmon\DAL\IDAL>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
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 18
    public static function find($id, array $columns = ['*'], $options = [])
143
    {
144
        // Return a cached instance if one exists
145 18
        $cache = self::cache();
146 18
        if ($cache->containsAttributes($id, $columns)) {
147
            return $cache->get($id);
148
        }
149
150
        // Return attributes which are not cached
151 18
        $columns = $cache->getNotCachedAttributes($id, $columns);
152
153
        // Create a new model
154 18
        $model = static::createInstance();
155
        $model->setId($id);
156
157
        // Merge options
158
        $options = array_merge($options, ['columns' => $columns == ['*'] ? [] : $columns]);
159
160
        // Get by id
161
        try {
162
            $model->_dal->get($id, $options);
163
        } catch (Missing404Exception $e) {
164
            return null;
165
        }
166
167
        // Fill internal attributes
168
        $model->_exist = true;
169
170
        // Put model to cache
171
        $model = $cache->put($id, $model, $columns);
172
173
        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
        if (is_null($model)) {
186
            $model = static::createInstance();
187
            $model->setId($id);
188
        }
189
        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
        if (is_null($model)) {
204
            throw new ModelNotFoundException(get_called_class(), $id);
205
        }
206
        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
        if (array_key_exists('id', $attributes)) {
221
            $model->setId($attributes['id']);
222
        }
223
224
        $model->fill($attributes);
225
226
        $model->save();
227
228
        return $model;
229
    }
230
231
    /**
232
     * Destroy the models by the given id.
233
     *
234
     * @param mixed $id
235
     */
236
    public static function destroy($id)
237
    {
238
        $ids = is_array($id) ? $id : [$id];
239
        foreach ($ids as $id) {
240
            $model = static::find($id);
241
            if (!is_null($model)) {
242
                $model->delete();
243
            }
244
        }
245
    }
246
}
247