Completed
Pull Request — develop (#89)
by Ionut
02:31
created

BaseRepository::getConnection()   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
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/*
4
 * NOTICE OF LICENSE
5
 *
6
 * Part of the Rinvex Repository Package.
7
 *
8
 * This source file is subject to The MIT License (MIT)
9
 * that is bundled with this package in the LICENSE file.
10
 *
11
 * Package: Rinvex Repository Package
12
 * License: The MIT License (MIT)
13
 * Link:    https://rinvex.com
14
 */
15
16
namespace Rinvex\Repository\Repositories;
17
18
use Closure;
19
use Rinvex\Repository\Traits\Cacheable;
20
use Illuminate\Contracts\Container\Container;
21
use Rinvex\Repository\Contracts\CacheableContract;
22
use Rinvex\Repository\Contracts\RepositoryContract;
23
24
abstract class BaseRepository implements RepositoryContract, CacheableContract
25
{
26
    use Cacheable;
27
28
    /**
29
     * The IoC container instance.
30
     *
31
     * @var \Illuminate\Contracts\Container\Container
32
     */
33
    protected $container;
34
35
    /**
36
     * The connection name for the repository.
37
     *
38
     * @var string
39
     */
40
    protected $connection;
41
42
    /**
43
     * The repository identifier.
44
     *
45
     * @var string
46
     */
47
    protected $repositoryId;
48
49
    /**
50
     * The repository model.
51
     *
52
     * @var string
53
     */
54
    protected $model;
55
56
    /**
57
     * The relations to eager load on query execution.
58
     *
59
     * @var array
60
     */
61
    protected $relations = [];
62
63
    /**
64
     * The query where clauses.
65
     *
66
     * @var array
67
     */
68
    protected $where = [];
69
70
    /**
71
     * The query whereIn clauses.
72
     *
73
     * @var array
74
     */
75
    protected $whereIn = [];
76
77
    /**
78
     * The query whereNotIn clauses.
79
     *
80
     * @var array
81
     */
82
    protected $whereNotIn = [];
83
84
    /**
85
     * The query whereHas clauses.
86
     *
87
     * @var array
88
     */
89
    protected $whereHas = [];
90
91
    /**
92
     * The "offset" value of the query.
93
     *
94
     * @var int
95
     */
96
    protected $offset;
97
98
    /**
99
     * The "limit" value of the query.
100
     *
101
     * @var int
102
     */
103
    protected $limit;
104
105
    /**
106
     * The column to order results by.
107
     *
108
     * @var array
109
     */
110
    protected $orderBy = [];
111
112
    /**
113
     * The query having clauses.
114
     *
115
     * @var array
116
     */
117
    protected $havings = [];
118
119
    /**
120
     * Execute given callback and return the result.
121
     *
122
     * @param string   $class
123
     * @param string   $method
124
     * @param array    $args
125
     * @param \Closure $closure
126
     *
127
     * @return mixed
128
     */
129
    protected function executeCallback($class, $method, $args, Closure $closure)
130
    {
131
        $skipUri = $this->getContainer('config')->get('rinvex.repository.cache.skip_uri');
132
133
        // Check if cache is enabled
134
        if ($this->getCacheLifetime() && ! $this->getContainer('request')->has($skipUri)) {
135
            return $this->cacheCallback($class, $method, $args, $closure);
136
        }
137
138
        // Cache disabled, just execute query & return result
139
        $result = call_user_func($closure);
140
141
        // We're done, let's clean up!
142
        $this->resetRepository();
143
144
        return $result;
145
    }
146
147
    /**
148
     * Reset repository to it's defaults.
149
     *
150
     * @return $this
151
     */
152
    protected function resetRepository()
153
    {
154
        $this->relations  = [];
155
        $this->where      = [];
156
        $this->whereIn    = [];
157
        $this->whereNotIn = [];
158
        $this->whereHas   = [];
159
        $this->offset     = null;
160
        $this->limit      = null;
161
        $this->orderBy    = [];
162
        $this->havings    = [];
163
164
        return $this;
165
    }
166
167
    /**
168
     * Prepare query.
169
     *
170
     * @param object $model
171
     *
172
     * @return object
173
     */
174
    protected function prepareQuery($model)
175
    {
176
        // Set the relationships that should be eager loaded
177
        if (! empty($this->relations)) {
178
            $model = $model->with($this->relations);
179
        }
180
181
        // Add a basic where clause to the query
182
        foreach ($this->where as $where) {
183
            list($attribute, $operator, $value, $boolean) = array_pad($where, 4, null);
184
185
            $model = $model->where($attribute, $operator, $value, $boolean);
186
        }
187
188
        // Add a "where in" clause to the query
189
        foreach ($this->whereIn as $whereIn) {
190
            list($attribute, $values, $boolean, $not) = array_pad($whereIn, 4, null);
191
192
            $model = $model->whereIn($attribute, $values, $boolean, $not);
193
        }
194
195
        // Add a "where not in" clause to the query
196
        foreach ($this->whereNotIn as $whereNotIn) {
197
            list($attribute, $values, $boolean) = array_pad($whereNotIn, 3, null);
198
199
            $model = $model->whereNotIn($attribute, $values, $boolean);
200
        }
201
202
        // Add a "where has" clause to the query
203
        foreach ($this->whereHas as $whereHas) {
204
            list($relation, $callback, $operator, $count) = array_pad($whereHas, 4, null);
205
206
            $model = $model->whereHas($relation, $callback, $operator, $count);
207
        }
208
209
        // Set the "offset" value of the query
210
        if ($this->offset > 0) {
211
            $model = $model->offset($this->offset);
212
        }
213
214
        // Set the "limit" value of the query
215
        if ($this->limit > 0) {
216
            $model = $model->limit($this->limit);
217
        }
218
219
        // Add an "order by" clause to the query.
220
        if (! empty($this->orderBy)) {
221
            list($attribute, $direction) = $this->orderBy;
222
223
            $model = $model->orderBy($attribute, $direction);
224
        }
225
226
        // Add a "having" clause to the query
227
        foreach ($this->havings as $having) {
228
            list($column, $operator, $value, $boolean) = array_pad($having, 4, null);
229
230
            $model = $model->having($column, $operator, $value, $boolean);
231
        }
232
233
        return $model;
234
    }
235
236
    /**
237
     * {@inheritdoc}
238
     */
239
    public function setContainer(Container $container)
240
    {
241
        $this->container = $container;
242
243
        return $this;
244
    }
245
246
    /**
247
     * {@inheritdoc}
248
     */
249
    public function getContainer($service = null)
250
    {
251
        return is_null($service) ? ($this->container ?: app()) : ($this->container[$service] ?: app($service));
252
    }
253
254
    /**
255
     * {@inheritdoc}
256
     */
257
    public function setConnection($name)
258
    {
259
        $this->connection = $name;
260
261
        return $this;
262
    }
263
264
    /**
265
     * {@inheritdoc}
266
     */
267
    public function getConnection()
268
    {
269
        return $this->connection;
270
    }
271
272
    /**
273
     * {@inheritdoc}
274
     */
275
    public function setRepositoryId($repositoryId)
276
    {
277
        $this->repositoryId = $repositoryId;
278
279
        return $this;
280
    }
281
282
    /**
283
     * {@inheritdoc}
284
     */
285
    public function getRepositoryId()
286
    {
287
        return $this->repositoryId ?: get_called_class();
288
    }
289
290
    /**
291
     * {@inheritdoc}
292
     */
293
    public function setModel($model)
294
    {
295
        $this->model = $model;
296
297
        return $this;
298
    }
299
300
    /**
301
     * {@inheritdoc}
302
     */
303
    public function getModel()
304
    {
305
        $model = $this->getContainer('config')->get('rinvex.repository.models');
306
307
        return $this->model ?: str_replace(['Repositories', 'Repository'], [$model, ''], get_called_class());
308
    }
309
310
    /**
311
     * {@inheritdoc}
312
     */
313
    public function getModelInstance($id)
314
    {
315
        return $id ? $this->find($id) : $this->createModel();
316
    }
317
318
    /**
319
     * {@inheritdoc}
320
     */
321
    public function with($relations)
322
    {
323
        if (is_string($relations)) {
324
            $relations = func_get_args();
325
        }
326
327
        $this->relations = $relations;
328
329
        return $this;
330
    }
331
332
    /**
333
     * {@inheritdoc}
334
     */
335
    public function where($attribute, $operator = null, $value = null, $boolean = 'and')
336
    {
337
        // The last `$boolean` expression is intentional to fix list() & array_pad() results
338
        $this->where[] = [$attribute, $operator, $value, $boolean ?: 'and'];
339
340
        return $this;
341
    }
342
343
    /**
344
     * {@inheritdoc}
345
     */
346
    public function whereIn($attribute, $values, $boolean = 'and', $not = false)
347
    {
348
        // The last `$boolean` & `$not` expressions are intentional to fix list() & array_pad() results
349
        $this->whereIn[] = [$attribute, $values, $boolean ?: 'and', (bool) $not];
350
351
        return $this;
352
    }
353
354
    /**
355
     * {@inheritdoc}
356
     */
357
    public function whereNotIn($attribute, $values, $boolean = 'and')
358
    {
359
        // The last `$boolean` expression is intentional to fix list() & array_pad() results
360
        $this->whereNotIn[] = [$attribute, $values, $boolean ?: 'and'];
361
362
        return $this;
363
    }
364
365
    /**
366
     * {@inheritdoc}
367
     */
368
    public function whereHas($relation, Closure $callback, $operator = '>=', $count = 1)
369
    {
370
        // The last `$operator` & `$count` expressions are intentional to fix list() & array_pad() results
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
371
        $this->whereHas[] = [$relation, $callback, $operator ?: '>=', $count ?: 1];
372
373
        return $this;
374
    }
375
376
    /**
377
     * {@inheritdoc}
378
     */
379
    public function offset($offset)
380
    {
381
        $this->offset = $offset;
382
383
        return $this;
384
    }
385
386
    /**
387
     * {@inheritdoc}
388
     */
389
    public function limit($limit)
390
    {
391
        $this->limit = $limit;
392
393
        return $this;
394
    }
395
396
    /**
397
     * {@inheritdoc}
398
     */
399
    public function orderBy($attribute, $direction = 'asc')
400
    {
401
        $this->orderBy = [$attribute, $direction];
402
403
        return $this;
404
    }
405
406
    /**
407
     * {@inheritdoc}
408
     */
409
    public function having($column, $operator = null, $value = null, $boolean = 'and')
410
    {
411
        $this->havings[] = [$column, $operator, $value, $boolean ?: 'and'];
412
413
        return $this;
414
    }
415
416
    /**
417
     * {@inheritdoc}
418
     */
419
    public function store($id, array $attributes = [])
420
    {
421
        return ! $id ? $this->create($attributes) : $this->update($id, $attributes);
422
    }
423
424
    /**
425
     * {@inheritdoc}
426
     */
427
    public static function __callStatic($method, $parameters)
428
    {
429
        return call_user_func_array([new static(), $method], $parameters);
430
    }
431
432
    /**
433
     * {@inheritdoc}
434
     */
435
    public function __call($method, $parameters)
436
    {
437
        return call_user_func_array([$this->createModel(), $method], $parameters);
438
    }
439
}
440