Completed
Push — master ( c52149...a01f44 )
by
unknown
03:28
created

TagDependencyTrait::objectTag()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.9256

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 17
ccs 8
cts 12
cp 0.6667
rs 8.8571
cc 5
eloc 10
nc 3
nop 1
crap 5.9256
1
<?php
2
3
namespace DevGroup\TagDependencyHelper;
4
5
use Yii;
6
use yii\caching\TagDependency;
7
use yii\db\ActiveRecord;
8
9
/**
10
 * TagDependencyTrait features:
11
 * - retrieving common and object tags
12
 * - configuring cache component(through overriding getTagDependencyCacheComponent)
13
 * - configuring composite tags(through overriding cacheCompositeTagFields)
14
 * - Identity Map pattern support
15
 */
16
trait TagDependencyTrait
17
{
18
    /** @var array IdentityMap pattern support */
19
    public static $identityMap = [];
20
21
    /**
22
     * @return \yii\caching\Cache
23
     */
24 2
    public function getTagDependencyCacheComponent()
25
    {
26 2
        return Yii::$app->cache;
27
    }
28
29
    /**
30
     * Returns common tag name for model instance
31
     * @return string tag name
32
     */
33 2
    public static function commonTag()
34
    {
35
        /** @var \yii\db\ActiveRecord $this */
36 2
        return NamingHelper::getCommonTag(static::className());
37
    }
38
39
    /**
40
     * Returns object tag name including it's id
41
     * @param array $oldFields Changed fields from Update Event
42
     * @return string tag name
43
     */
44 2
    public function objectTag($oldFields = [])
45
    {
46
        /** @var \yii\db\ActiveRecord $this */
47 2
        $primaryKey = null;
0 ignored issues
show
Unused Code introduced by
$primaryKey is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
48 2
        if (count($this->primaryKey()) === 1)
49 2
        {
50 2
            $key = $this->primaryKey()[0];
51 2
            $primaryKey = isset($oldFields[$key]) ? $oldFields[$key] : $this->$key;
52 2
        } else {
53
            $primaryKey = [];
54
            foreach ($this->primaryKey() as $key)
55
            {
56
                $primaryKey[$key] = isset($oldFields[$key]) ? $oldFields[$key] : $this->$key;
57
            }
58
        }
59 2
        return NamingHelper::getObjectTag($this->className(), $primaryKey);
60
    }
61
62
    /**
63
     * Returns composite tags name including fields
64
     * @param array $oldFields Changed fields from Update Event
65
     * @return array tag names
66
     */
67 1
    public function objectCompositeTag($oldFields = [])
68
    {
69
        /** @var \yii\db\ActiveRecord|TagDependencyTrait $this */
70 1
        $cacheFields = $this->cacheCompositeTagFields();
71
72 1
        if(empty($cacheFields)) {
73 1
            return [];
74
        }
75
76 1
        $cacheFields = (is_array($cacheFields) && !empty($cacheFields) && is_array($cacheFields[0])) ? $cacheFields : [$cacheFields];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
77 1
        $tags = [];
78
79 1
        foreach ($cacheFields as $tagFields) {
80 1
            $tag = [];
81 1
            $changed = false;
82
83 1 View Code Duplication
            foreach ($tagFields as $tagField) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
84 1
                $tag[$tagField] = $this->$tagField;
85 1
                $changed |= isset($oldFields[$tagField]);
86 1
            }
87
88 1
            $tags[] = NamingHelper::getCompositeTag($this->className(), $tag);
89
90 1
            if ($changed) {
91
                $tag = [];
92 View Code Duplication
                foreach ($tagFields as $tagField) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
93
                    $tag[$tagField] = isset($oldFields[$tagField]) ? $oldFields[$tagField] : $this->$tagField;
94
                }
95
                $tags[] = NamingHelper::getCompositeTag($this->className(), $tag);
0 ignored issues
show
Bug introduced by
It seems like className() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
96
            }
97 1
        }
98
99 1
        return $tags;
100
    }
101
102
    /**
103
     * Specific fields from model for build composite tags for invalidate
104
     * Example:
105
     * return [
106
     *  ['field1', 'field2'],
107
     *  ['field1', 'field2', 'field3'],
108
     * ];
109
     * @return array
110
     */
111 2
    protected function cacheCompositeTagFields()
112
    {
113 2
        return [];
114
    }
115
116
    /**
117
     * Finds or creates new model using or not using cache(objectTag is applied)
118
     * @param string|int $id ID of model to find
119
     * @param bool $createIfEmptyId Create new model instance(record) if id is empty
120
     * @param bool $useCache Use cache
121
     * @param int $cacheLifetime Cache lifetime in seconds
122
     * @param bool|\Exception $throwException False or exception instance to throw if model not found or (empty id AND createIfEmptyId==false)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 142 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
123
     * @param bool $useIdentityMap True if we want to use identity map
124
     * @return \yii\db\ActiveRecord|null|self|TagDependencyTrait
125
     * @throws \Exception
126
     */
127 1
    public static function loadModel(
128
        $id,
129
        $createIfEmptyId = false,
130
        $useCache = true,
131
        $cacheLifetime = 86400,
132
        $throwException = false,
133
        $useIdentityMap = false
134
    ) {
135
        /** @var \yii\db\ActiveRecord|TagDependencyTrait $model */
136 1
        $model = null;
137 1
        if (empty($id)) {
138 1
            if ($createIfEmptyId === true) {
139 1
                $model = new static;
140 1
            } else {
141 1
                if ($throwException !== false) {
142 1
                    throw $throwException;
143
                } else {
144 1
                    return null;
145
                }
146
            }
147 1
        } elseif ($useIdentityMap === true) {
148
            if (isset(static::$identityMap[$id])) {
149
                return static::$identityMap[$id];
150
            }
151
        }
152
153 1
        if ($useCache === true && $model===null) {
154 1
            $model = Yii::$app->cache->get(static::className() . ":" . $id);
155 1
        }
156 1
        if (!is_object($model)) {
157 1
            $model = static::findOne($id);
158
159 1
            if ($model !== null) {
160 1
                if ($useIdentityMap === true) {
161
                    static::$identityMap[$model->id] = &$model;
162
                }
163 1
                if ($useCache === true) {
164 1
                    Yii::$app->cache->set(
165 1
                        static::className() . ":" . $id,
166 1
                        $model,
167 1
                        $cacheLifetime,
168 1
                        new TagDependency([
169 1
                            'tags' => $model->objectTag(),
170 1
                        ])
171 1
                    );
172 1
                }
173 1
            }
174 1
        }
175 1
        if (!is_object($model)) {
176 1
            if ($throwException) {
177 1
                throw $throwException;
178
            } else {
179 1
                return null;
180
            }
181
        }
182 1
        return $model;
183
    }
184
185
    /**
186
     * Invalidate model tags.
187
     * @param yii\db\AfterSaveEvent|null $event when called as an event handler.
188
     * @return bool
189
     */
190 2
    public function invalidateTags($event = null)
191
    {
192
        /** @var TagDependencyTrait $this */
193 2
        $oldFields = $event !== null && $event->name === ActiveRecord::EVENT_AFTER_UPDATE ? $event->changedAttributes : [];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
194 2
        \yii\caching\TagDependency::invalidate(
195 2
            $this->getTagDependencyCacheComponent(),
196
            [
197 2
                static::commonTag(),
198 2
                $this->objectTag($oldFields)
199 2
            ]
200 2
        );
201
202 2
        if (!empty($this->cacheCompositeTagFields())) {
203 1
            \yii\caching\TagDependency::invalidate(
204 1
                $this->getTagDependencyCacheComponent(),
205 1
                $this->objectCompositeTag($oldFields)
206 1
            );
207 1
        }
208
209 2
        return true;
210
    }
211
212
}
213