CacheableActiveRecord::attach()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 9.6666
1
<?php
2
3
namespace DevGroup\TagDependencyHelper;
4
5
use Yii;
6
use yii\base\Behavior;
7
use yii\base\InvalidConfigException;
8
use yii\db\ActiveRecord;
9
10
/**
11
 * Helper for yii\db\ActiveRecord models
12
 * Features:
13
 * - automatically invalidate cache based on unified tag names
14
 *
15
 * This behavior needs TagDependencyTrait to be added to model!
16
 */
17
class CacheableActiveRecord extends Behavior
18
{
19
    /**
20
     * Get events list.
21
     * @return array
22
     */
23 2
    public function events()
24
    {
25
        return [
26 2
            ActiveRecord::EVENT_AFTER_DELETE => [$this->owner, 'invalidateTags'],
27 2
            ActiveRecord::EVENT_AFTER_INSERT => [$this->owner, 'invalidateTags'],
28 2
            ActiveRecord::EVENT_AFTER_UPDATE => [$this->owner, 'invalidateTags'],
29 2
        ];
30
    }
31
32
    /**
33
     * @inheritdoc
34
     */
35 3
    public function attach($owner)
36
    {
37 3
        if ($owner->hasMethod('commonTag', false) === false) {
38 1
            throw new InvalidConfigException(
39 1
                Yii::t('app', 'You should add TagDependencyTrait to your model class {class}', ['class'=>$owner->className()])
40 1
            );
41
        }
42 2
        return parent::attach($owner);
43
    }
44
45
}
46