CacheableTrait::cacheDuration()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Suitmedia\Cacheable\Traits\Repository;
4
5
use Illuminate\Support\Str;
6
use Suitmedia\Cacheable\Contracts\CacheableModel;
7
8
trait CacheableTrait
9
{
10
    /**
11
     * Get the base class name, without 'Repository' suffix.
12
     *
13
     * @return string
14
     */
15
    protected function baseClassName(): string
16
    {
17
        $class = class_basename(get_class($this));
18
19
        if (Str::endsWith($class, 'Repository')) {
20
            $class = substr($class, 0, -10);
21
        }
22
23
        return $class;
24
    }
25
26
    /**
27
     * Return the cache duration value in seconds,
28
     * which would be used by the repository.
29
     *
30
     * @return int
31
     */
32
    public function cacheDuration(): int
33
    {
34
        if (property_exists($this, 'cacheDuration')) {
35
            return (int) static::$cacheDuration;
36
        }
37
38
        return (int) config('cacheable.duration');
39
    }
40
41
    /**
42
     * Return an array of method names which
43
     * you don't wish to be cached.
44
     *
45
     * @return array
46
     */
47
    public function cacheExcept(): array
48
    {
49
        $result = (array) config('cacheable.except');
50
51
        if (property_exists($this, 'cacheExcept')) {
52
            $result = array_unique(array_merge($result, (array) static::$cacheExcept));
53
        }
54
55
        return $result;
56
    }
57
58
    /**
59
     * Generate cache key.
60
     *
61
     * @param string $method
62
     * @param mixed  $args
63
     *
64
     * @return string
65
     */
66
    public function cacheKey($method, $args): string
67
    {
68
        $class = $this->baseClassName();
69
        $args = sha1(serialize($args));
70
71
        return implode(':', [$class, $method, $args]);
72
    }
73
74
    /**
75
     * Return the cache tags which would
76
     * be used by the repository.
77
     *
78
     * @return mixed
79
     */
80
    public function cacheTags()
81
    {
82
        if (property_exists($this, 'cacheTags')) {
83
            return (array) static::$cacheTags;
84
        }
85
86
        return $this->model()->cacheTags();
87
    }
88
89
    /**
90
     * Return the primary model object which would
91
     * be used by the repository.
92
     *
93
     * @return \Suitmedia\Cacheable\Contracts\CacheableModel
94
     */
95
    abstract public function model(): CacheableModel;
96
}
97