Completed
Push — master ( 6f8a5e...9697ab )
by Mike
08:21
created

CachedBuilder::find()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 8
Ratio 100 %

Importance

Changes 0
Metric Value
dl 8
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
1
<?php namespace GeneaLabs\LaravelModelCaching;
2
3
use Closure;
4
use Illuminate\Cache\TaggableStore;
5
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
6
use Illuminate\Database\Eloquent\Relations\Pivot;
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
10
class CachedBuilder extends EloquentBuilder
11
{
12
    protected function cache(array $tags = [])
13
    {
14
        $cache = cache();
15
16
        if (is_subclass_of($cache->getStore(), TaggableStore::class)) {
17
            $cache = $cache->tags($tags);
18
        }
19
20
        return $cache;
21
    }
22
23
    protected function getCacheKey(array $columns = ['*'], $idColumn = null) : string
24
    {
25
        $key = $this->getModelSlug();
26
        $key .= $this->getIdColumn($idColumn ?: '');
27
        $key .= $this->getQueryColumns($columns);
28
        $key .= $this->getWhereClauses();
29
        $key .= $this->getWithModels();
30
        $key .= $this->getOffsetClause();
31
        $key .= $this->getLimitClause();
32
33
        return $key;
34
    }
35
36
    protected function getIdColumn(string $idColumn) : string
37
    {
38
        return $idColumn ? "_{$idColumn}" : '';
39
    }
40
41
    protected function getLimitClause() : string
42
    {
43
        if (! $this->query->limit) {
44
            return '';
45
        }
46
47
        return "-limit_{$this->query->limit}";
48
    }
49
50
    protected function getModelSlug() : string
51
    {
52
        return str_slug(get_class($this->model));
53
    }
54
55
    protected function getOffsetClause() : string
56
    {
57
        if (! $this->query->offset) {
58
            return '';
59
        }
60
61
        return "-offset_{$this->query->offset}";
62
    }
63
64
    protected function getQueryColumns(array $columns) : string
65
    {
66
        if ($columns === ['*'] || $columns === []) {
67
            return '';
68
        }
69
70
        return '_' . implode('_', $columns);
71
    }
72
73
    protected function getWhereClauses() : string
74
    {
75
        return collect($this->query->wheres)->reduce(function ($carry, $where) {
76
            $value = $where['value'] ?? implode('_', $where['values']) ?? '';
77
78
            return "{$carry}-{$where['column']}_{$value}";
79
        }) ?: '';
80
    }
81
82
    protected function getWithModels() : string
83
    {
84
        $eagerLoads = collect($this->eagerLoad);
85
86
        if ($eagerLoads->isEmpty()) {
87
            return '';
88
        }
89
90
        return '-' . implode('-', $eagerLoads->keys()->toArray());
91
    }
92
93
    protected function getCacheTags() : array
94
    {
95
        return collect($this->eagerLoad)->keys()
96
            ->map(function ($name) {
97
                return str_slug(get_class(
98
                    $this->model
99
                        ->{$name}()
100
                        ->getQuery()
101
                        ->model
102
                ));
103
            })
104
            ->prepend(str_slug(get_class($this->model)))
105
            ->values()
106
            ->toArray();
107
    }
108
109 View Code Duplication
    public function avg($column)
110
    {
111
        $tags = [str_slug(get_class($this->model))];
112
        $key = str_slug(get_class($this->model)) ."-avg_{$column}";
113
114
        return $this->cache($tags)
115
            ->rememberForever($key, function () use ($column) {
116
                return parent::avg($column);
1 ignored issue
show
Bug introduced by
The method avg() does not exist on Illuminate\Database\Eloquent\Builder. It seems like you code against a sub-type of Illuminate\Database\Eloquent\Builder such as GeneaLabs\LaravelModelCaching\CachedBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

116
                return parent::/** @scrutinizer ignore-call */ avg($column);
Loading history...
117
            });
118
    }
119
120 View Code Duplication
    public function count($columns = ['*'])
121
    {
122
        $tags = [str_slug(get_class($this->model))];
123
        $key = str_slug(get_class($this->model)) ."-count";
124
125
        return $this->cache($tags)
126
            ->rememberForever($key, function () use ($columns) {
127
                return parent::count($columns);
1 ignored issue
show
Bug introduced by
The method count() does not exist on Illuminate\Database\Eloquent\Builder. It seems like you code against a sub-type of Illuminate\Database\Eloquent\Builder such as GeneaLabs\LaravelModelCaching\CachedBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

127
                return parent::/** @scrutinizer ignore-call */ count($columns);
Loading history...
128
            });
129
    }
130
131 View Code Duplication
    public function cursor()
132
    {
133
        $tags = [str_slug(get_class($this->model))];
134
        $key = str_slug(get_class($this->model)) ."-cursor";
135
136
        return $this->cache($tags)
137
            ->rememberForever($key, function () {
138
                return collect(parent::cursor());
139
            });
140
    }
141
142
    /**
143
     * @SuppressWarnings(PHPMD.ShortVariable)
144
     */
145 View Code Duplication
    public function find($id, $columns = ['*'])
146
    {
147
        $tags = $this->getCacheTags();
148
        $key = $this->getCacheKey($columns, $id);
149
150
        return $this->cache($tags)
151
            ->rememberForever($key, function () use ($id, $columns) {
152
                return parent::find($id, $columns);
153
            });
154
    }
155
156 View Code Duplication
    public function first($columns = ['*'])
157
    {
158
        $tags = $this->getCacheTags();
159
        $key = $this->getCacheKey($columns) . '-first';
160
161
        return $this->cache($tags)
162
            ->rememberForever($key, function () use ($columns) {
163
                return parent::first($columns);
164
            });
165
    }
166
167 View Code Duplication
    public function get($columns = ['*'])
168
    {
169
        $tags = $this->getCacheTags();
170
        $key = $this->getCacheKey($columns);
171
172
        return $this->cache($tags)
173
            ->rememberForever($key, function () use ($columns) {
174
                return parent::get($columns);
175
            });
176
    }
177
178 View Code Duplication
    public function max($column)
179
    {
180
        $tags = [str_slug(get_class($this->model))];
181
        $key = str_slug(get_class($this->model)) ."-max_{$column}";
182
183
        return $this->cache($tags)
184
            ->rememberForever($key, function () use ($column) {
185
                return parent::max($column);
1 ignored issue
show
Bug introduced by
The method max() does not exist on Illuminate\Database\Eloquent\Builder. It seems like you code against a sub-type of Illuminate\Database\Eloquent\Builder such as GeneaLabs\LaravelModelCaching\CachedBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

185
                return parent::/** @scrutinizer ignore-call */ max($column);
Loading history...
186
            });
187
    }
188
189 View Code Duplication
    public function min($column)
190
    {
191
        $tags = [str_slug(get_class($this->model))];
192
        $key = str_slug(get_class($this->model)) ."-min_{$column}";
193
194
        return $this->cache($tags)
195
            ->rememberForever($key, function () use ($column) {
196
                return parent::min($column);
1 ignored issue
show
Bug introduced by
The method min() does not exist on Illuminate\Database\Eloquent\Builder. It seems like you code against a sub-type of Illuminate\Database\Eloquent\Builder such as GeneaLabs\LaravelModelCaching\CachedBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

196
                return parent::/** @scrutinizer ignore-call */ min($column);
Loading history...
197
            });
198
    }
199
200
    public function pluck($column, $key = null)
201
    {
202
        $tags = $this->getCacheTags();
203
        $cacheKey = $this->getCacheKey([$column]) . "-pluck_{$column}";
204
205
        if ($key) {
206
            $cacheKey .= "_{$key}";
207
        }
208
209
        return $this->cache($tags)
210
            ->rememberForever($cacheKey, function () use ($column, $key) {
211
                return parent::pluck($column, $key);
212
            });
213
    }
214
215 View Code Duplication
    public function sum($column)
216
    {
217
        $tags = [str_slug(get_class($this->model))];
218
        $key = str_slug(get_class($this->model)) ."-sum_{$column}";
219
220
        return $this->cache($tags)
221
            ->rememberForever($key, function () use ($column) {
222
                return parent::sum($column);
1 ignored issue
show
Bug introduced by
The method sum() does not exist on Illuminate\Database\Eloquent\Builder. It seems like you code against a sub-type of Illuminate\Database\Eloquent\Builder such as GeneaLabs\LaravelModelCaching\CachedBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

222
                return parent::/** @scrutinizer ignore-call */ sum($column);
Loading history...
223
            });
224
    }
225
}
226