-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathCounterCacheBehavior.php
More file actions
419 lines (380 loc) · 13.8 KB
/
CounterCacheBehavior.php
File metadata and controls
419 lines (380 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM\Behavior;
use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\ORM\Association;
use Cake\ORM\Association\BelongsTo;
use Cake\ORM\Behavior;
use Cake\ORM\Query\SelectQuery;
use Closure;
/**
* CounterCache behavior
*
* Enables models to cache the amount of connections in a given relation.
*
* Examples with Post model belonging to User model
*
* Regular counter cache
* ```
* [
* 'Users' => [
* 'post_count'
* ]
* ]
* ```
*
* Counter cache with scope
* ```
* [
* 'Users' => [
* 'posts_published' => [
* 'conditions' => [
* 'published' => true
* ]
* ]
* ]
* ]
* ```
*
* Counter cache using custom find
* ```
* [
* 'Users' => [
* 'posts_published' => [
* 'finder' => 'published' // Will be using findPublished()
* ]
* ]
* ]
* ```
*
* Counter cache using lambda function returning the count
* This is equivalent to example #2
*
* ```
* [
* 'Users' => [
* 'posts_published' => function (EventInterface $event, EntityInterface $entity, Table $table) {
* $query = $table->find('all')->where([
* 'published' => true,
* 'user_id' => $entity->get('user_id')
* ]);
* return $query->count();
* }
* ]
* ]
* ```
*
* When using a lambda function you can return `false` to disable updating the counter value
* for the current operation.
*
* Ignore updating the field if it is dirty
* ```
* [
* 'Users' => [
* 'posts_published' => [
* 'ignoreDirty' => true
* ]
* ]
* ]
* ```
*
* You can disable counter updates entirely by sending the `ignoreCounterCache` option
* to your save operation:
*
* ```
* $this->Articles->save($article, ['ignoreCounterCache' => true]);
* ```
*/
class CounterCacheBehavior extends Behavior
{
/**
* Store the fields which should be ignored
*
* @var array<string, array<string, bool>>
*/
protected array $_ignoreDirty = [];
/**
* beforeSave callback.
*
* Check if a field, which should be ignored, is dirty
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event The beforeSave event that was fired
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @param \ArrayObject<string, mixed> $options The options for the query
* @return void
*/
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) {
return;
}
foreach ($this->_config as $assoc => $settings) {
$assoc = $this->_table->getAssociation($assoc);
/** @var string|int $field */
foreach ($settings as $field => $config) {
if (is_int($field)) {
continue;
}
$registryAlias = $assoc->getTarget()->getRegistryAlias();
$entityAlias = $assoc->getProperty();
/** @var \Cake\Datasource\EntityInterface $assocEntity */
$assocEntity = $entity->$entityAlias;
if (
!is_callable($config) &&
isset($config['ignoreDirty']) &&
$config['ignoreDirty'] === true &&
$assocEntity->isDirty($field)
) {
$this->_ignoreDirty[$registryAlias][$field] = true;
}
}
}
}
/**
* afterSave callback.
*
* Makes sure to update counter cache when a new record is created or updated.
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event The afterSave event that was fired.
* @param \Cake\Datasource\EntityInterface $entity The entity that was saved.
* @param \ArrayObject<string, mixed> $options The options for the query
* @return void
*/
public function afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) {
return;
}
$this->_processAssociations($event, $entity);
$this->_ignoreDirty = [];
}
/**
* afterDelete callback.
*
* Makes sure to update counter cache when a record is deleted.
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event The afterDelete event that was fired.
* @param \Cake\Datasource\EntityInterface $entity The entity that was deleted.
* @param \ArrayObject<string, mixed> $options The options for the query
* @return void
*/
public function afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
if (isset($options['ignoreCounterCache']) && $options['ignoreCounterCache'] === true) {
return;
}
$this->_processAssociations($event, $entity);
}
/**
* Update counter cache for a batch of records.
*
* Counter caches configured to use closures will not be updated by the method.
*
* @param string|null $assocName The association name to update counter cache for.
* If null, all configured associations will be processed.
* @param int $limit The number of records to update per page/iteration.
* @param int|null $page The page/iteration number. If null (default), all
* records will be updated one page at a time.
* @return void
* @since 5.2.0
*/
public function updateCounterCache(?string $assocName = null, int $limit = 100, ?int $page = null): void
{
$config = $this->_config;
if ($assocName !== null) {
$config = [$assocName => $config[$assocName]];
}
foreach ($config as $assoc => $settings) {
/** @var \Cake\ORM\Association\BelongsTo<\Cake\ORM\Table> $belongsTo */
$belongsTo = $this->_table->getAssociation($assoc);
foreach ($settings as $field => $config) {
if ($config instanceof Closure) {
// Cannot update counter cache which use a closure
return;
}
if (is_int($field)) {
$field = $config;
$config = [];
}
$this->updateCountForAssociation($belongsTo, $field, $config, $limit, $page);
}
}
}
/**
* Update counter cache for the given association.
*
* @param \Cake\ORM\Association\BelongsTo<\Cake\ORM\Table> $assoc The association object.
* @param string $field Counter cache field.
* @param array $config Config array.
* @param int $limit Limit.
* @param int|null $page Page number.
* @return void
*/
protected function updateCountForAssociation(
BelongsTo $assoc,
string $field,
array $config,
int $limit = 100,
?int $page = null,
): void {
$primaryKeys = (array)$assoc->getBindingKey();
/** @var array<string> $foreignKeys */
$foreignKeys = (array)$assoc->getForeignKey();
$query = $assoc->getTarget()->find()
->select($primaryKeys)
->limit($limit);
foreach ($primaryKeys as $key) {
$query->orderByAsc($key);
}
$singlePage = $page !== null;
$page ??= 1;
do {
$results = $query
->page($page++)
->all();
/** @var \Cake\Datasource\EntityInterface $entity */
foreach ($results as $entity) {
$updateConditions = $entity->extract($primaryKeys);
foreach ($updateConditions as $f => $value) {
if ($value === null) {
$updateConditions[$f . ' IS'] = $value;
unset($updateConditions[$f]);
}
}
$countConditions = array_combine($foreignKeys, $updateConditions);
$count = $this->_getCount($config, $countConditions);
$assoc->getTarget()->updateAll([$field => $count], $updateConditions);
}
} while (!$singlePage && $results->count() === $limit);
}
/**
* Iterate all associations and update counter caches.
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event instance.
* @param \Cake\Datasource\EntityInterface $entity Entity.
* @return void
*/
protected function _processAssociations(EventInterface $event, EntityInterface $entity): void
{
foreach ($this->_config as $assoc => $settings) {
$assoc = $this->_table->getAssociation($assoc);
$this->_processAssociation($event, $entity, $assoc, $settings);
}
}
/**
* Updates counter cache for a single association
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event instance.
* @param \Cake\Datasource\EntityInterface $entity Entity
* @param \Cake\ORM\Association $assoc The association object
* @param array $settings The settings for counter cache for this association
* @return void
* @throws \RuntimeException If invalid callable is passed.
*/
protected function _processAssociation(
EventInterface $event,
EntityInterface $entity,
Association $assoc,
array $settings,
): void {
/** @var array<string> $foreignKeys */
$foreignKeys = (array)$assoc->getForeignKey();
$countConditions = $entity->extract($foreignKeys);
foreach ($countConditions as $field => $value) {
if ($value === null) {
$countConditions[$field . ' IS'] = $value;
unset($countConditions[$field]);
}
}
$primaryKeys = (array)$assoc->getBindingKey();
$updateConditions = array_combine($primaryKeys, $countConditions);
$countOriginalConditions = $entity->extractOriginalChanged($foreignKeys);
$updateOriginalConditions = null;
if ($countOriginalConditions !== []) {
$updateOriginalConditions = array_combine($primaryKeys, $countOriginalConditions);
}
foreach ($settings as $field => $config) {
if (is_int($field)) {
$field = $config;
$config = [];
}
if (
isset($this->_ignoreDirty[$assoc->getTarget()->getRegistryAlias()][$field]) &&
$this->_ignoreDirty[$assoc->getTarget()->getRegistryAlias()][$field] === true
) {
continue;
}
if ($this->_shouldUpdateCount($updateConditions)) {
if ($config instanceof Closure) {
$count = $config($event, $entity, $this->_table, false);
} else {
$count = $this->_getCount($config, $countConditions);
}
if ($count !== false) {
$assoc->getTarget()->updateAll([$field => $count], $updateConditions);
}
}
if ($updateOriginalConditions && $this->_shouldUpdateCount($updateOriginalConditions)) {
if ($config instanceof Closure) {
$count = $config($event, $entity, $this->_table, true);
} else {
$count = $this->_getCount($config, $countOriginalConditions);
}
if ($count !== false) {
$assoc->getTarget()->updateAll([$field => $count], $updateOriginalConditions);
}
}
}
}
/**
* Checks if the count should be updated given a set of conditions.
*
* @param array $conditions Conditions to update count.
* @return bool True if the count update should happen, false otherwise.
*/
protected function _shouldUpdateCount(array $conditions): bool
{
return !empty(array_filter($conditions, function ($value) {
return $value !== null;
}));
}
/**
* Fetches and returns the count for a single field in an association
*
* @param array<string, mixed> $config The counter cache configuration for a single field
* @param array $conditions Additional conditions given to the query
* @return \Cake\ORM\Query\SelectQuery<\Cake\Datasource\EntityInterface|array>|int The query to fetch the number of
* relations matching the given config and conditions or the number itself.
*/
protected function _getCount(array $config, array $conditions): SelectQuery|int
{
$finder = 'all';
if (!empty($config['finder'])) {
$finder = $config['finder'];
unset($config['finder']);
}
$config['conditions'] = array_merge($conditions, $config['conditions'] ?? []);
$query = $this->_table->find($finder, ...$config);
if (isset($config['useSubQuery']) && $config['useSubQuery'] === false) {
return $query->count();
}
return $query
->select(['count' => $query->func()->count('*')], true)
->orderBy([], true);
}
}