Completed
Push — master ( 5e51f5...c9193b )
by Marco
13:02
created

ModelManager::__clone()   A

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 0
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
    /**
87
     * Add a basic where clause to the query.
88
     *
89
     * @return $this
90
     */
91
    public function where()
92
    {
93
        $this->query->where(...func_get_args());
94
        return $this;
95
    }
96
97
    public function update($values)
98
    {
99
        return $this->getQuery()->update($this->addUpdatedAtColumn($values));
100
    }
101
102
    /**
103
     * Get a single column's value from the first result of a query.
104
     *
105
     * @param  string $column
106
     * @return mixed
107
     */
108
    public function value($column)
109
    {
110
        if ($result = $this->first([$column])) {
111
            return $result->{$column};
112
        }
113
    }
114
115
    /**
116
     * Execute the query as a "select" statement.
117
     *
118
     * @param  array $columns
119
     * @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...
120
     */
121
    public function get($columns = ['*'])
122
    {
123
        return $this->query->get($columns);
124
    }
125
126
    /**
127
     * Get the hydrated models without eager loading.
128
     *
129
     * @param  array $columns
130
     * @return \Childish\ChildishModel[]
131
     */
132
    public function getModels($columns = ['*'])
133
    {
134
        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...
135
            $this->query->get($columns)->all()
136
        )->all();
137
    }
138
139
    /**
140
     * Create a collection of models from plain arrays.
141
     *
142
     * @param  array $items
143
     * @return \Childish\support\Collection
144
     */
145
    public function hydrate(array $items)
146
    {
147
        $instance = $this->newModelInstance();
148
149
        return $instance->newCollection(array_map(function ($item) use ($instance) {
150
            return $instance->newFromBuilder($item);
151
        }, $items));
152
    }
153
154
    /**
155
     * Create a new instance of the model being queried.
156
     *
157
     * @param  array $attributes
158
     * @return \Childish\ChildishModel
159
     */
160
    public function newModelInstance($attributes = [])
161
    {
162
        return $this->model->newInstance($attributes)->setConnection(
163
            $this->query->getConnection()->getName()
164
        );
165
    }
166
167
168
    /**
169
     * Execute the query and get the first result.
170
     *
171
     * @param  array $columns
172
     * @return \Childish\ChildishModel|static|null
173
     */
174
    public function first($columns = ['*'])
175
    {
176
        return $this->take(1)->get($columns)->first();
177
    }
178
179
    /**
180
     * Alias to set the "limit" value of the query.
181
     *
182
     * @param  int $value
183
     * @return \Childish\query\Builder|static
184
     */
185
    public function take($value)
186
    {
187
        return $this->limit($value);
188
    }
189
190
    /**
191
     * Set the "limit" value of the query.
192
     *
193
     * @param  int $value
194
     * @return $this
195
     */
196
    public function limit($value)
197
    {
198
        $property = $this->unions ? 'unionLimit' : 'limit';
199
200
        if ($value >= 0) {
201
            $this->$property = $value;
202
        }
203
204
        return $this;
205
    }
206
207
208
    /**
209
     * Get the underlying query builder instance.
210
     *
211
     * @return \Childish\query\Builder
212
     */
213
    public function getQuery()
214
    {
215
        return $this->query;
216
    }
217
218
    /**
219
     * Set the underlying query builder instance.
220
     *
221
     * @param  \Childish\query\Builder $query
222
     * @return $this
223
     */
224
    public function setQuery($query)
225
    {
226
        $this->query = $query;
227
228
        return $this;
229
    }
230
231
232
    /**
233
     * Add the "updated at" column to an array of values.
234
     *
235
     * @param  array $values
236
     * @return array
237
     */
238
    protected function addUpdatedAtColumn(array $values)
239
    {
240
        if (!$this->model->timestamps) {
241
            return $values;
242
        }
243
244
        return Tools::add(
245
            $values, $this->model->getUpdatedAtColumn(),
246
            $this->model->freshTimestampString()
247
        );
248
    }
249
250
    /**
251
     * Increment a column's value by a given amount.
252
     *
253
     * @param  string $column
254
     * @param  int    $amount
255
     * @param  array  $extra
256
     * @return int
257
     */
258
    public function increment($column, $amount = 1, array $extra = [])
259
    {
260
        return $this->getQuery()->increment(
261
            $column, $amount, $this->addUpdatedAtColumn($extra)
262
        );
263
    }
264
265
    /**
266
     * Delete a record from the database.
267
     *
268
     * @return mixed
269
     */
270
    public function delete()
271
    {
272
        return $this->getQuery()->delete();
273
    }
274
275
    /**
276
     * Dynamically handle calls into the query instance.
277
     *
278
     * @param  string $method
279
     * @param  array  $parameters
280
     * @return mixed
281
     */
282
    public function __call($method, $parameters)
283
    {
284
        if (in_array($method, $this->passthru)) {
285
            return $this->getQuery()->{$method}(...$parameters);
286
        }
287
        $this->query->{$method}(...$parameters);
288
        return $this;
289
    }
290
291
    /**
292
     * Force a clone of the underlying query builder when cloning.
293
     *
294
     * @return void
295
     */
296
    public function __clone()
297
    {
298
        $this->query = clone $this->query;
299
    }
300
}