Completed
Push — master ( fd5849...c99aaa )
by Renato
05:53
created

CacheableRepository::setCacheRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace NwLaravel\Repositories\Eloquent;
3
4
use Illuminate\Contracts\Cache\Repository as CacheRepository;
5
use Prettus\Repository\Contracts\CriteriaInterface;
6
use ReflectionObject;
7
use Exception;
8
9
/**
10
 * Class CacheableRepository
11
 */
12
trait CacheableRepository
13
{
14
    /**
15
     * @var CacheRepository
16
     */
17
    protected $cacheRepository = null;
18
19
    /**
20
     * @var boolean
21
     */
22
    protected $cacheSkip = false;
23
24
    /**
25
     * Set Cache Repository
26
     *
27
     * @param CacheRepository $repository
28
     *
29
     * @return $this
30
     */
31 1
    public function setCacheRepository(CacheRepository $repository)
32
    {
33 1
        $this->cacheRepository = $repository;
34
35 1
        return $this;
36
    }
37
38
    /**
39
     * Return instance of Cache Repository
40
     *
41
     * @return CacheRepository
42
     */
43 1
    public function getCacheRepository()
44
    {
45 1
        if (is_null($this->cacheRepository)) {
46 1
            $this->cacheRepository = app(config('repository.cache.repository', 'cache'));
47 1
        }
48
49 1
        return $this->cacheRepository;
50
    }
51
52
    /**
53
     * CacheTags
54
     *
55
     * @param mixed $tags
56
     *
57
     * @return \Illuminate\Cache\TaggedCache
58
     */
59 1
    public function cacheTags($tags = null)
60
    {
61 1
        $tags = empty($tags) ? get_called_class() : $tags;
62
63 1
        return $this->getCacheRepository()->tags($tags);
64
    }
65
66
    /**
67
     * Skip Cache
68
     *
69
     * @param bool $status
70
     *
71
     * @return $this
72
     */
73 1
    public function skipCache($status = true)
74
    {
75 1
        $this->cacheSkip = $status;
76
77 1
        return $this;
78
    }
79
80
    /**
81
     * Is Skipped Cache
82
     *
83
     * @return bool
84
     */
85 2
    public function isSkippedCache()
86
    {
87 2
        $skipped = isset($this->cacheSkip) ? $this->cacheSkip : false;
88 2
        $request = app('Illuminate\Http\Request');
89 2
        $skipCacheParam = config('repository.cache.params.skipCache', 'skipCache');
90
91 2
        if ($request->has($skipCacheParam) && $request->get($skipCacheParam)) {
92 1
            $skipped = true;
93 1
        }
94
95 2
        return $skipped;
96
    }
97
98
    /**
99
     * Allowed Cache
100
     *
101
     * @param string $method
102
     *
103
     * @return bool
104
     */
105 1
    protected function allowedCache($method)
106
    {
107 1
        $cacheEnabled = config('repository.cache.enabled', true);
108
109 1
        if (!$cacheEnabled) {
110
            return false;
111
        }
112
113 1
        $cacheOnly = isset($this->cacheOnly) ? $this->cacheOnly : config('repository.cache.allowed.only', null);
0 ignored issues
show
Bug introduced by
The property cacheOnly does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
114 1
        $cacheExcept = isset($this->cacheExcept) ? $this->cacheExcept : config('repository.cache.allowed.except', null);
0 ignored issues
show
Bug introduced by
The property cacheExcept does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
115
116 1
        if (is_array($cacheOnly)) {
117
            return in_array($method, $cacheOnly);
118
        }
119
120 1
        if (is_array($cacheExcept)) {
121
            return !in_array($method, $cacheExcept);
122
        }
123
124 1
        if (is_null($cacheOnly) && is_null($cacheExcept)) {
125 1
            return true;
126
        }
127
128
        return false;
129
    }
130
131
    /**
132
     * Get Cache key for the method
133
     *
134
     * @param string $method
135
     * @param array  $args
136
     *
137
     * @return string
138
     */
139 1
    public function getCacheKey($method, $args = null)
140
    {
141
142 1
        $request = app('Illuminate\Http\Request');
143 1
        $args = serialize($args);
144 1
        $criteria = $this->serializeCriteria();
145
        
146 1
        return sprintf('%s@%s-%s', get_called_class(), $method, md5($args . $criteria . $request->fullUrl()));
147
    }
148
149
    /**
150
     * Serialize the criteria making sure the Closures are taken care of.
151
     *
152
     * @return string
153
     */
154 1
    protected function serializeCriteria()
155
    {
156
        try {
157 1
            return serialize($this->getCriteria());
0 ignored issues
show
Bug introduced by
The method getCriteria() does not exist on NwLaravel\Repositories\E...ent\CacheableRepository. Did you maybe mean getByCriteria()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
158
        } catch (Exception $e) {
159
            return serialize($this->getCriteria()->map(function ($criterion) {
0 ignored issues
show
Bug introduced by
The method getCriteria() does not exist on NwLaravel\Repositories\E...ent\CacheableRepository. Did you maybe mean getByCriteria()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
160
                return $this->serializeCriterion($criterion);
161
            }));
162
        }
163
    }
164
165
    /**
166
     * Serialize single criterion with customized serialization of Closures.
167
     *
168
     * @param  \Prettus\Repository\Contracts\CriteriaInterface $criterion
169
     *
170
     * @return \Prettus\Repository\Contracts\CriteriaInterface|array
171
     *
172
     * @throws \Exception
173
     */
174
    protected function serializeCriterion($criterion)
175
    {
176
        try {
177
            serialize($criterion);
178
179
            return $criterion;
180
        } catch (Exception $e) {
181
            // We want to take care of the closure serialization errors,
182
            // other than that we will simply re-throw the exception.
183
            if ($e->getMessage() !== "Serialization of 'Closure' is not allowed") {
184
                throw $e;
185
            }
186
187
            $reflection = new ReflectionObject($criterion);
188
189
            return [
190
                'hash' => md5((string) $reflection),
191
                'properties' => $reflection->getProperties(),
192
            ];
193
        }
194
    }
195
196
    /**
197
     * Get cache minutes
198
     *
199
     * @return int
200
     */
201 1
    public function getCacheMinutes()
202
    {
203 1
        $cacheMinutes = isset($this->cacheMinutes) ? $this->cacheMinutes : config('repository.cache.minutes', 30);
0 ignored issues
show
Bug introduced by
The property cacheMinutes does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
204
205 1
        return $cacheMinutes;
206
    }
207
208
    /**
209
     * call Cache
210
     *
211
     * @param string $method
212
     * @param array  $args
213
     *
214
     * @return mixed
215
     */
216 1
    public function callCache($method, array $args)
217
    {
218 1
        if (!$this->allowedCache($method) || $this->isSkippedCache()) {
219
            return call_user_func_array(['parent', $method], $args);
220
        }
221
222 1
        $key = $this->getCacheKey($method, $args);
223 1
        $minutes = $this->getCacheMinutes();
224 1
        $value = $this->cacheTags()->remember($key, $minutes, function () use ($method, $args) {
225
            return call_user_func_array(['parent', $method], $args);
226 1
        });
227
228 1
        return $value;
229
    }
230
231
    /**
232
     * Retrieve all data of repository
233
     *
234
     * @param array $columns
235
     *
236
     * @return mixed
237
     */
238 1
    public function all($columns = ['*'])
0 ignored issues
show
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
239
    {
240 1
        return $this->callCache(__FUNCTION__, func_get_args());
241
    }
242
243
    /**
244
     * Retrieve all data of repository, paginated
245
     *
246
     * @param null  $limit
247
     * @param array $columns
248
     *
249
     * @return mixed
250
     */
251 1
    public function paginate($limit = null, $columns = ['*'])
0 ignored issues
show
Unused Code introduced by
The parameter $limit is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
252
    {
253 1
        return $this->callCache(__FUNCTION__, func_get_args());
254
    }
255
256
    /**
257
     * Find data by id
258
     *
259
     * @param int   $id
260
     * @param array $columns
261
     *
262
     * @return mixed
263
     */
264 1
    public function find($id, $columns = ['*'])
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
265
    {
266 1
        return $this->callCache(__FUNCTION__, func_get_args());
267
    }
268
269
    /**
270
     * Find data by field and value
271
     *
272
     * @param string $field
273
     * @param mixed  $value
274
     * @param array  $columns
275
     *
276
     * @return mixed
277
     */
278 1
    public function findByField($field, $value = null, $columns = ['*'])
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
279
    {
280 1
        return $this->callCache(__FUNCTION__, func_get_args());
281
    }
282
283
    /**
284
     * Find data by multiple fields
285
     *
286
     * @param array $where
287
     * @param array $columns
288
     *
289
     * @return mixed
290
     */
291 1
    public function findWhere(array $where, $columns = ['*'])
0 ignored issues
show
Unused Code introduced by
The parameter $where is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
292
    {
293 1
        return $this->callCache(__FUNCTION__, func_get_args());
294
    }
295
296
    /**
297
     * Find data by Criteria
298
     *
299
     * @param CriteriaInterface $criteria
300
     *
301
     * @return mixed
302
     */
303 1
    public function getByCriteria(CriteriaInterface $criteria)
0 ignored issues
show
Unused Code introduced by
The parameter $criteria is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
304
    {
305 1
        return $this->callCache(__FUNCTION__, func_get_args());
306
    }
307
308
    /**
309
     * Pluck
310
     *
311
     * @param string $column
312
     * @param array  $key
313
     *
314
     * @return array
315
     */
316 1
    public function pluck($column, $key = null)
0 ignored issues
show
Unused Code introduced by
The parameter $column is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
317
    {
318 1
        return $this->callCache(__FUNCTION__, func_get_args());
319
    }
320
321
    /**
322
     * Count
323
     *
324
     * @param array $input Array Input
325
     *
326
     * @return int
327
     */
328 1
    public function count(array $input = array())
0 ignored issues
show
Unused Code introduced by
The parameter $input is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
329
    {
330 1
        return $this->callCache(__FUNCTION__, func_get_args());
331
    }
332
333
    /**
334
     * Max
335
     *
336
     * @param mixed $field Mixed Field
337
     * @param array $input Array Input
338
     *
339
     * @return mixed
340
     */
341 1
    public function max($field, array $input = array())
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $input is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
342
    {
343 1
        return $this->callCache(__FUNCTION__, func_get_args());
344
    }
345
346
    /**
347
     * Min
348
     *
349
     * @param mixed $field Mixed Field
350
     * @param array $input Array Input
351
     *
352
     * @return mixed
353
     */
354 1
    public function min($field, array $input = array())
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $input is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
355
    {
356 1
        return $this->callCache(__FUNCTION__, func_get_args());
357
    }
358
359
    /**
360
     * Sum
361
     *
362
     * @param mixed $field Mixed Field
363
     * @param array $input Array Input
364
     *
365
     * @return float
366
     */
367 1
    public function sum($field, array $input = array())
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $input is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
368
    {
369 1
        return $this->callCache(__FUNCTION__, func_get_args());
370
    }
371
372
    /**
373
     * Average
374
     *
375
     * @param mixed $field Mixed Field
376
     * @param array $input Array Input
377
     *
378
     * @return float
379
     */
380 1
    public function avg($field, array $input = array())
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $input is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
381
    {
382 1
        return $this->callCache(__FUNCTION__, func_get_args());
383
    }
384
}
385