Completed
Pull Request — master (#26)
by Mike
02:50
created

CachedBuilder::getMethodKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
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->getOrderByClauses();
31
        $key .= $this->getOffsetClause();
32
        $key .= $this->getLimitClause();
33
34
        return $key;
35
    }
36
37
    protected function getIdColumn(string $idColumn) : string
38
    {
39
40
        return $idColumn ? "_{$idColumn}" : '';
41
    }
42
43
    protected function getLimitClause() : string
44
    {
45
        if (! $this->query->limit) {
46
            return '';
47
        }
48
49
        return "-limit_{$this->query->limit}";
50
    }
51
52
    protected function getModelSlug() : string
53
    {
54
        return str_slug(get_class($this->model));
55
    }
56
57
    protected function getOffsetClause() : string
58
    {
59
        if (! $this->query->offset) {
60
            return '';
61
        }
62
63
        return "-offset_{$this->query->offset}";
64
    }
65
66
    protected function getQueryColumns(array $columns) : string
67
    {
68
        if ($columns === ['*'] || $columns === []) {
69
            return '';
70
        }
71
72
        return '_' . implode('_', $columns);
73
    }
74
75
    protected function getWhereClauses(array $wheres = []) : string
76
    {
77
        $wheres = collect($wheres);
78
79
        if ($wheres->isEmpty()) {
80
            $wheres = collect($this->query->wheres);
81
        }
82
83
        return $wheres->reduce(function ($carry, $where) {
84
            if (in_array($where['type'], ['Exists', 'Nested', 'NotExists'])) {
85
                return '_' . strtolower($where['type']) . $this->getWhereClauses($where['query']->wheres);
86
            }
87
88
            if ($where['type'] === 'Column') {
89
                return "_{$where['boolean']}_{$where['first']}_{$where['operator']}_{$where['second']}";
90
            }
91
92
            if ($where['type'] === 'raw') {
93
                return "_{$where['boolean']}_" . str_slug($where['sql']);
94
            }
95
96
            $value = array_get($where, 'value');
97
            $value .= in_array($where['type'], ['In', 'Null', 'NotNull'])
98
                ? strtolower($where['type'])
99
                : '';
100
            $value .= is_array(array_get($where, 'values'))
101
                ? '_' . implode('_', $where['values'])
102
                : '';
103
104
            return "{$carry}-{$where['column']}_{$value}";
105
        }) ?: '';
106
    }
107
108
    protected function getWithModels() : string
109
    {
110
        $eagerLoads = collect($this->eagerLoad);
111
112
        if ($eagerLoads->isEmpty()) {
113
            return '';
114
        }
115
116
        return '-' . implode('-', $eagerLoads->keys()->toArray());
117
    }
118
119
	protected function getOrderByClauses(){
120
        $orders = collect($this->query->orders);
121
122
        return $orders->reduce(function($carry, $order){
123
            return $carry . '_orderBy_' . $order['column'] . '_' . $order['direction'];
124
        });
125
    }
126
127
    protected function getMethodKey(string $postfix = null) : string
128
    {
129
        return str_slug(get_class($this->model)) . $postfix;
130
    }
131
132
    protected function getModelTag() : array
133
    {
134
        return [str_slug(get_class($this->model))];
135
    }
136
137
    protected function getCacheTags() : array
138
    {
139
        return collect($this->eagerLoad)->keys()
140
            ->map(function ($relationName) {
141
                $relation = collect(explode('.', $relationName))
142
                    ->reduce(function ($carry, $name) {
143
                        if (! $carry) {
144
                            $carry = $this->model;
145
                        }
146
147
                        if ($carry instanceof Relation) {
148
                            $carry = $carry->getQuery()->model;
149
                        }
150
151
                        return $carry->{$name}();
152
                    });
153
154
                return str_slug(get_class($relation->getQuery()->model));
155
            })
156
            ->prepend(str_slug(get_class($this->model)))
157
            ->values()
158
            ->toArray();
159
    }
160
161 View Code Duplication
    public function avg($column)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
    {
163
        return $this->cache($this->getModelTag())
164
            ->rememberForever($this->getMethodKey("-avg_{$column}"), function () use ($column) {
165
                return parent::avg($column);
166
            });
167
    }
168
169 View Code Duplication
    public function count($columns = ['*'])
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
    {
171
        return $this->cache($this->getModelTag())
172
            ->rememberForever($this->getMethodKey("-count"), function () use ($columns) {
173
                return parent::count($columns);
174
            });
175
    }
176
177
    public function cursor()
178
    {
179
        return $this->cache($this->getModelTag())
180
            ->rememberForever($this->getMethodKey("-cursor"), function () {
181
                return collect(parent::cursor());
182
            });
183
    }
184
185
    /**
186
     * @SuppressWarnings(PHPMD.ShortVariable)
187
     */
188 View Code Duplication
    public function find($id, $columns = ['*'])
189
    {
190
        return $this->cache($this->getCacheTags())
191
            ->rememberForever($this->getCacheKey($columns, $id), function () use ($id, $columns) {
192
                return parent::find($id, $columns);
193
            });
194
    }
195
196 View Code Duplication
    public function first($columns = ['*'])
197
    {
198
        return $this->cache($this->getCacheTags())
199
            ->rememberForever($this->getCacheKey($columns) . '-first', function () use ($columns) {
200
                return parent::first($columns);
201
            });
202
    }
203
204 View Code Duplication
    public function get($columns = ['*'])
205
    {
206
        return $this->cache($this->getCacheTags())
207
            ->rememberForever($this->getCacheKey($columns), function () use ($columns) {
208
                return parent::get($columns);
209
            });
210
    }
211
212 View Code Duplication
    public function max($column)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
    {
214
        return $this->cache($this->getModelTag())
215
            ->rememberForever($this->getMethodKey("-max_{$column}"), function () use ($column) {
216
                return parent::max($column);
217
            });
218
    }
219
220 View Code Duplication
    public function min($column)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
221
    {
222
        return $this->cache($this->getModelTag())
223
            ->rememberForever($this->getMethodKey("-min_{$column}"), function () use ($column) {
224
                return parent::min($column);
225
            });
226
    }
227
228
    public function pluck($column, $key = null)
229
    {
230
        $cacheKey = $this->getCacheKey([$column]) . "-pluck_{$column}";
231
232
        if ($key) {
233
            $cacheKey .= "_{$key}";
234
        }
235
236
        return $this->cache($this->getCacheTags())
237
            ->rememberForever($cacheKey, function () use ($column, $key) {
238
                return parent::pluck($column, $key);
239
            });
240
    }
241
242 View Code Duplication
    public function sum($column)
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
243
    {
244
        return $this->cache($this->getModelTag())
245
            ->rememberForever($this->getMethodKey("-sum_{$column}"), function () use ($column) {
246
                return parent::sum($column);
247
            });
248
    }
249
}
250