Behavior::getTagDependency()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Yii2 AR Tag Cache.
4
 *
5
 * This file contains behavior class.
6
 *
7
 * @author  Aleksei Korotin <[email protected]>
8
 */
9
namespace herroffizier\yii2artc;
10
11
use Yii;
12
use yii\db\ActiveRecord;
13
use yii\caching\TagDependency;
14
15
class Behavior extends \yii\base\Behavior
16
{
17
    /**
18
     * Cache component.
19
     *
20
     * @var string
21
     */
22
    public $cache = 'cache';
23
24 12
    public function events()
25
    {
26
        return [
27 12
            ActiveRecord::EVENT_AFTER_INSERT => 'invalidateCache',
28 12
            ActiveRecord::EVENT_AFTER_UPDATE => 'invalidateCache',
29 12
            ActiveRecord::EVENT_AFTER_DELETE => 'invalidateCache',
30 8
        ];
31
    }
32
33
    /**
34
     * Get array of tags for dependency.
35
     *
36
     * @return string[]
37
     */
38 9
    protected function getCacheTags()
39
    {
40 9
        $classes = [$this->owner];
41
42 9
        $tags = TagBuilder::buildTags($classes);
43
44 9
        return $tags;
45
    }
46
47
    /**
48
     * Invalidate cache for current model.
49
     */
50 9
    public function invalidateCache()
51
    {
52 9
        $tags = $this->getCacheTags();
53
54 9
        TagDependency::invalidate(Yii::$app->get($this->cache), $tags);
55 9
    }
56
57
    /**
58
     * Get tag dependency for current ActiveRecord class.
59
     *
60
     * @return Dependency
0 ignored issues
show
Documentation introduced by
Should the return type not be TagDependency?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
61
     */
62 9
    public function getTagDependency()
63
    {
64 9
        $tags = $this->getCacheTags();
65
66 9
        return new TagDependency(['tags' => $tags]);
67
    }
68
}
69