ModelManager::insert()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Childish\database;
3
4
use Childish\ChildishModel;
5
use Childish\query\Builder;
6
use Childish\support\Tools;
7
8
/**
9
 * ModelManager
10
 *
11
 * @author    Pu ShaoWei <[email protected]>
12
 * @date      2017/12/13
13
 * @package   Childish\database
14
 * @version   1.0
15
 */
16
class ModelManager
17
{
18
    /**
19
     * The base query builder instance.
20
     *
21
     * @var \Childish\query\Builder
22
     */
23
    protected $query;
24
25
    /**
26
     * The model being queried.
27
     *
28
     * @var \Childish\ChildishModel
29
     */
30
    protected $model;
31
32
    /**
33
     * The query union statements.
34
     *
35
     * @var array
36
     */
37
    public $unions;
38
    /**
39
     * The methods that should be returned from query builder.
40
     *
41
     * @var array
42
     */
43
    protected $passthru = [
44
        'insert', 'insertGetId', 'getBindings', 'toSql',
45
        'exists', 'count', 'min', 'max', 'avg', 'sum', 'getConnection',
46
    ];
47
48
49
    /**
50
     * Create a new Eloquent query builder instance.
51
     *
52
     * @param  \Childish\query\Builder $query
53
     * @return mixed|void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
54
     */
55
    public function __construct(Builder $query)
56
    {
57
        $this->query = $query;
58
    }
59
60
    /**
61
     * Set a model instance for the model being queried.
62
     *
63
     * @param  \Childish\ChildishModel $model
64
     * @return $this
65
     */
66
    public function setModel(ChildishModel $model)
67
    {
68
        $this->model = $model;
69
70
        $this->query->from($model->getTable());
71
72
        return $this;
73
    }
74
75
    /**
76
     * Get the model instance being queried.
77
     *
78
     * @return \Childish\ChildishModel
79
     */
80
    public function getModel()
81
    {
82
        return $this->model;
83
    }
84
85
    /**
86
     * update
87
     *
88
     * @param $values
89
     * @return int
90
     */
91
    public function update($values)
92
    {
93
        return $this->getQuery()->update($this->addUpdatedAtColumn($values));
94
    }
95
96
    /**
97
     * insert
98
     *
99
     * @param $values
100
     * @return int
101
     */
102
    public function insert($values)
103
    {
104
        return $this->getQuery()->insert($this->addInsertedAtColumn($values));
105
    }
106
107
    /**
108
     * insertGetId
109
     *
110
     * @param $values
111
     * @return int
112
     */
113
    public function insertGetId($values)
114
    {
115
        return $this->getQuery()->insertGetId($this->addInsertedAtColumn($values));
116
    }
117
118
    /**
119
     * updateOrInsert
120
     *
121
     * @param $values
122
     * @return bool
123
     */
124
    public function updateOrInsert($values)
125
    {
126
        return $this->getQuery()->updateOrInsert($this->addInsertedAtColumn($values));
127
    }
128
129
    /**
130
     * Get a single column's value from the first result of a query.
131
     *
132
     * @param  string $column
133
     * @return mixed
134
     */
135
    public function value($column)
136
    {
137
        if ($result = $this->first([$column])) {
138
            return $result->{$column};
139
        }
140
    }
141
142
    /**
143
     * Execute the query as a "select" statement.
144
     *
145
     * @param  array $columns
146
     * @return \Childish\support\Collection|static[]\
0 ignored issues
show
Documentation introduced by
The doc-type \Childish\support\Collection|static[]\ could not be parsed: Expected "|" or "end of type", but got "\" at position 37. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
147
     */
148
    public function get($columns = ['*'])
149
    {
150
        return $this->query->get($columns);
151
    }
152
153
    /**
154
     * Get the hydrated models without eager loading.
155
     *
156
     * @param  array $columns
157
     * @return \Childish\ChildishModel[]
158
     */
159
    public function getModels($columns = ['*'])
160
    {
161
        return $this->model->hydrate(
0 ignored issues
show
Bug introduced by
The method hydrate() does not seem to exist on object<Childish\ChildishModel>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
162
            $this->query->get($columns)->all()
163
        )->all();
164
    }
165
166
    /**
167
     * Create a collection of models from plain arrays.
168
     *
169
     * @param  array $items
170
     * @return \Childish\support\Collection
171
     */
172
    public function hydrate(array $items)
173
    {
174
        $instance = $this->newModelInstance();
175
176
        return $instance->newCollection(array_map(function ($item) use ($instance) {
177
            return $instance->newFromBuilder($item);
178
        }, $items));
179
    }
180
181
    /**
182
     * Create a new instance of the model being queried.
183
     *
184
     * @param  array $attributes
185
     * @return \Childish\ChildishModel
186
     */
187
    public function newModelInstance($attributes = [])
188
    {
189
        return $this->model->newInstance($attributes)->setConnection(
190
            $this->query->getConnection()->getName()
191
        );
192
    }
193
194
195
    /**
196
     * Execute the query and get the first result.
197
     *
198
     * @param  array $columns
199
     * @return \Childish\ChildishModel|static|null
200
     */
201
    public function first($columns = ['*'])
202
    {
203
        return $this->take(1)->get($columns)->first();
204
    }
205
206
    /**
207
     * Alias to set the "limit" value of the query.
208
     *
209
     * @param  int $value
210
     * @return \Childish\query\Builder|static
211
     */
212
    public function take($value)
213
    {
214
        return $this->limit($value);
215
    }
216
217
    /**
218
     * Set the "limit" value of the query.
219
     *
220
     * @param  int $value
221
     * @return $this
222
     */
223
    public function limit($value)
224
    {
225
        $property = $this->unions ? 'unionLimit' : 'limit';
226
227
        if ($value >= 0) {
228
            $this->$property = $value;
229
        }
230
231
        return $this;
232
    }
233
234
235
    /**
236
     * Get the underlying query builder instance.
237
     *
238
     * @return \Childish\query\Builder
239
     */
240
    public function getQuery()
241
    {
242
        return $this->query;
243
    }
244
245
    /**
246
     * Set the underlying query builder instance.
247
     *
248
     * @param  \Childish\query\Builder $query
249
     * @return $this
250
     */
251
    public function setQuery($query)
252
    {
253
        $this->query = $query;
254
255
        return $this;
256
    }
257
258
259
    /**
260
     * Add the "updated at" column to an array of values.
261
     *
262
     * @param  array $values
263
     * @return array
264
     */
265
    protected function addUpdatedAtColumn(array $values)
266
    {
267
        if (!$this->model->timestamps) {
268
            return $values;
269
        }
270
271
        return Tools::add(
272
            $values, $this->model->getUpdatedAtColumn(),
273
            $this->model->freshTimestampString()
274
        );
275
    }
276
277
    /**
278
     * Add the "create_time at" column to an array of values.
279
     *
280
     * @param array $values
281
     * @return array
282
     */
283
    protected function addInsertedAtColumn(array $values)
284
    {
285
        if (!$this->model->timestamps) {
286
            return $values;
287
        }
288
289
        return Tools::add(
290
            $values, $this->model->getCreatedAtColumn(),
291
            $this->model->freshTimestampString()
292
        );
293
    }
294
295
296
    /**
297
     * Increment a column's value by a given amount.
298
     *
299
     * @param  string $column
300
     * @param  int    $amount
301
     * @param  array  $extra
302
     * @return int
303
     */
304
    public function increment($column, $amount = 1, array $extra = [])
305
    {
306
        return $this->getQuery()->increment(
307
            $column, $amount, $this->addUpdatedAtColumn($extra)
308
        );
309
    }
310
311
    /**
312
     * Delete a record from the database.
313
     *
314
     * @return mixed
315
     */
316
    public function delete()
317
    {
318
        return $this->getQuery()->delete();
319
    }
320
321
    /**
322
     * Dynamically handle calls into the query instance.
323
     *
324
     * @param  string $method
325
     * @param  array  $parameters
326
     * @return mixed
327
     */
328
    public function __call($method, $parameters)
329
    {
330
        if (in_array($method, $this->passthru)) {
331
            return $this->getQuery()->{$method}(...$parameters);
332
        }
333
        $this->query->{$method}(...$parameters);
334
        return $this;
335
    }
336
337
    /**
338
     * Force a clone of the underlying query builder when cloning.
339
     *
340
     * @return void
341
     */
342
    public function __clone()
343
    {
344
        $this->query = clone $this->query;
345
    }
346
}