Completed
Pull Request — master (#13)
by
unknown
35:28
created

TagDependencyTrait   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 195
Duplicated Lines 3.59 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 93.33%

Importance

Changes 6
Bugs 1 Features 4
Metric Value
wmc 33
c 6
b 1
f 4
lcom 1
cbo 4
dl 7
loc 195
ccs 70
cts 75
cp 0.9333
rs 9.3999

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getTagDependencyCacheComponent() 0 4 1
A commonTag() 0 5 1
B objectTag() 0 19 5
C objectCompositeTag() 7 34 7
A cacheCompositeTagFields() 0 4 1
C loadModel() 0 57 14
A invalidateTags() 0 20 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 2
     */
24
    public function getTagDependencyCacheComponent()
25 2
    {
26
        return Yii::$app->cache;
27
    }
28
29
    /**
30
     * Returns common tag name for model instance
31
     * @return string tag name
32 2
     */
33
    public static function commonTag()
34
    {
35 2
        /** @var \yii\db\ActiveRecord $this */
36
        return NamingHelper::getCommonTag(static::className());
37
    }
38
39
    /**
40
     * Returns object tag name including it's id
41
     * @return string tag name
42 2
     */
43
    public function objectTag()
44
    {
45 2
        /** @var \yii\db\ActiveRecord $this */
46
        $primary_key;
0 ignored issues
show
Bug introduced by
The variable $primary_key seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
47
        if (count($this->primaryKey()) == 1)
48
        {
49
            $key = $this->primaryKey()[0];
50
            $primary_key = isset($oldfields[$key]) ? $oldfields[$key] : $this->$key;
0 ignored issues
show
Bug introduced by
The variable $oldfields seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
51
        }
52 1
        else
53
        {
54
            $primary_key = [];
55 1
            foreach ($this->primaryKey() as $key)
56
            {
57 1
                $primary_key[$key] = isset($oldfields[$key]) ? $oldfields[$key] : $this->$key;
58 1
            }
59
        }
60
        return NamingHelper::getObjectTag($this->className(), $primary_key);
61 1
    }
62 1
63
    /**
64 1
     * Returns composite tags name including fields
65 1
     * @return array tag names
66
     */
67 1
    public function objectCompositeTag()
68 1
    {
69 1
        /** @var \yii\db\ActiveRecord|TagDependencyTrait $this */
70
        $cacheFields = $this->cacheCompositeTagFields();
71 1
72 1
        if(empty($cacheFields)) {
73
            return [];
74 1
        }
75
76
        $tags = [];
77
78
        foreach ($cacheFields as $tagFields) {
79
            $tag = [];
80
            $changed = false;
81
82 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...
83
                $tag[$tagField] = $this->$tagField;
84
                $changed |= isset($oldfields[$tagField]);
85
            }
86 2
87
            $tags[] = NamingHelper::getCompositeTag($this->className(), $tag);
88 2
89
            if ($changed)
90
            {
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
        }
98
99
        return $tags;
100
    }
101
102 1
    /**
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 1
    protected function cacheCompositeTagFields()
112 1
    {
113 1
        return [];
114 1
    }
115 1
116 1
    /**
117 1
     * Finds or creates new model using or not using cache(objectTag is applied)
118
     * @param string|int $id ID of model to find
119 1
     * @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 1
     * @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
    public static function loadModel(
128 1
        $id,
129 1
        $createIfEmptyId = false,
130 1
        $useCache = true,
131 1
        $cacheLifetime = 86400,
132 1
        $throwException = false,
133
        $useIdentityMap = false
134 1
    ) {
135 1
        /** @var \yii\db\ActiveRecord|TagDependencyTrait $model */
136
        $model = null;
137
        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 1
                } else {
144 1
                    return null;
145 1
                }
146 1
            }
147 1
        } elseif ($useIdentityMap === true) {
148 1
            if (isset(static::$identityMap[$id])) {
149 1
                return static::$identityMap[$id];
150 1
            }
151 1
        }
152 1
153
        if ($useCache === true && $model===null) {
154 1
            $model = Yii::$app->cache->get(static::className() . ":" . $id);
155
        }
156
        if (!is_object($model)) {
157 1
            $model = static::findOne($id);
158
159
            if ($model !== null) {
160
                if ($useIdentityMap === true) {
161
                    static::$identityMap[$model->id] = &$model;
162
                }
163
                if ($useCache === true) {
164 2
                    Yii::$app->cache->set(
165
                        static::className() . ":" . $id,
166
                        $model,
167
                        $cacheLifetime,
168 2
                        new TagDependency([
169 2
                            'tags' => $model->objectTag(),
170
                        ])
171 2
                    );
172 2
                }
173 2
            }
174 2
        }
175
        if (!is_object($model)) {
176 2
            if ($throwException) {
177 1
                throw $throwException;
178 1
            } else {
179 1
                return null;
180 1
            }
181 1
        }
182
        return $model;
183 2
    }
184
185
    /**
186
     * Invalidate model tags.
187
     * @return bool
188
     */
189
    public function invalidateTags($event)
190
    {
191
        /** @var TagDependencyTrait $this */
192
        \yii\caching\TagDependency::invalidate(
193
            $this->getTagDependencyCacheComponent(),
194
            [
195
                static::commonTag(),
196
                $this->objectTag($event->name == ActiveRecord::EVENT_AFTER_UPDATE ? $event->changedAttributes : [])
0 ignored issues
show
Unused Code introduced by
The call to TagDependencyTrait::objectTag() has too many arguments starting with $event->name == \yii\db\...gedAttributes : array().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
197
            ]
198
        );
199
200
        if (!empty($this->cacheCompositeTagFields())) {
201
            \yii\caching\TagDependency::invalidate(
202
                $this->getTagDependencyCacheComponent(),
203
                $this->objectCompositeTag($event->name == ActiveRecord::EVENT_AFTER_UPDATE ? $event->changedAttributes : [])
0 ignored issues
show
Unused Code introduced by
The call to TagDependencyTrait::objectCompositeTag() has too many arguments starting with $event->name == \yii\db\...gedAttributes : array().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 124 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...
204
            );
205
        }
206
207
        return true;
208
    }
209
210
}
211