Completed
Push — master ( 76c9ed...47b819 )
by vistart
10:25 queued 04:16
created

EntityTrait   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 309
Duplicated Lines 0 %

Coupling/Cohesion

Components 4
Dependencies 8

Test Coverage

Coverage 77.59%

Importance

Changes 21
Bugs 0 Features 0
Metric Value
wmc 45
c 21
b 0
f 0
lcom 4
cbo 8
dl 0
loc 309
ccs 90
cts 116
cp 0.7759
rs 8.3673

21 Methods

Rating   Name   Duplication   Size   Complexity  
A buildNoInitModel() 0 4 1
A getEntityRulesCacheKey() 0 4 1
A getEntityRulesCacheTag() 0 4 1
A getEntityBehaviorsCacheKey() 0 4 1
A getEntityBehaviorsCacheTag() 0 4 1
A rules() 0 4 1
A recordWarnings() 0 6 3
A __toString() 0 10 3
A instantiate() 0 10 3
A unsetSelfFields() 0 4 1
B unsetFields() 0 12 5
A enabledFields() 0 9 3
A behaviors() 0 4 1
A getCache() 0 5 2
A getEntityRules() 0 12 4
A setEntityRules() 0 11 2
A getEntityBehaviors() 0 11 4
A setEntityBehaviors() 0 10 2
A resetCacheKey() 0 8 2
A initEntityEvents() 0 11 2
A onInitCache() 0 10 2

How to fix   Complexity   

Complex Class

Complex classes like EntityTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EntityTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link http://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license http://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
use Yii;
16
17
/**
18
 * This trait must be used in class extended from ActiveRecord. The ActiveRecord
19
 * supports \yii\db\ActiveRecord, \yii\mongodb\ActiveRecord, \yii\redis\ActiveRecord.
20
 * @property array $entityRules
21
 * @property array $entityBehaviors
22
 * @version 2.0
23
 * @author vistart <[email protected]>
24
 */
25
trait EntityTrait
26
{
27
    use GUIDTrait,
28
        IDTrait,
29
        IPTrait,
30
        TimestampTrait;
31
32
    private $entityLocalRules = [];
33
    private $entityLocalBehaviors = [];
34
35
    /**
36
     * @var string cache key and tag prefix. the prefix is usually set to full
37
     * qualified class name.
38
     */
39
    public $cachePrefix = '';
40
    public static $eventNewRecordCreated = 'newRecordCreated';
41
    public static $cacheKeyEntityRules = 'entity_rules';
42
    public static $cacheTagEntityRules = 'tag_entity_rules';
43
    public static $cacheKeyEntityBehaviors = 'entity_behaviors';
44
    public static $cacheTagEntityBehaviors = 'tag_entity_behaviors';
45
46
    /**
47
     * @var string cache component id. 
48
     */
49
    public $cacheId = 'cache';
50
51
    /**
52
     * @var boolean Determines to skip initialization.
53
     */
54
    public $skipInit = false;
55
56
    /**
57
     * @var string the name of query class or sub-class.
58
     */
59
    public $queryClass;
60
61
    /**
62
     * @return \static New self without any initializations.
63
     */
64 51
    public static function buildNoInitModel()
65
    {
66 51
        return new static(['skipInit' => true]);
0 ignored issues
show
Unused Code introduced by
The call to EntityTrait::__construct() has too many arguments starting with array('skipInit' => true).

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...
67
    }
68
69
    /**
70
     * Populate and return the entity rules.
71
     * You should call this function in your extended class and merge the result
72
     * with your rules, instead of overriding it, unless you know the
73
     * consequences.
74
     * @return type
75
     */
76 49
    public function rules()
77
    {
78 49
        return $this->getEntityRules();
79
    }
80
81
    /**
82
     * Populate and return the entity behaviors.
83
     * You should call this function in your extended class and merge the result
84
     * with your behaviors, instead of overriding it, unless you know the
85
     * consequences.
86
     * @return type
87
     */
88 51
    public function behaviors()
89
    {
90 51
        return $this->getEntityBehaviors();
91
    }
92
93
    /**
94
     * Get cache component. If cache component is not configured, Yii::$app->cache
95
     * will be given.
96
     * @return \yii\caching\Cache cache component.
97
     */
98 51
    protected function getCache()
99
    {
100 51
        $cacheId = $this->cacheId;
101 51
        return empty($cacheId) ? Yii::$app->cache : Yii::$app->$cacheId;
102
    }
103
104
    /**
105
     * Get entity rules cache key.
106
     * @return string cache key.
107
     */
108 49
    public function getEntityRulesCacheKey()
109
    {
110 49
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityRules;
111
    }
112
113
    /**
114
     * Get entity rules cache tag.
115
     * @return string cache tag.
116
     */
117 15
    public function getEntityRulesCacheTag()
118
    {
119 15
        return static::className() . $this->cachePrefix . static::$cacheTagEntityRules;
120
    }
121
122
    /**
123
     * Get entity rules.
124
     * @return array rules.
125
     */
126 49
    public function getEntityRules()
127
    {
128 49
        $cache = $this->getCache();
129 49
        if ($cache) {
130 49
            $this->entityLocalRules = $cache->get($this->getEntityRulesCacheKey());
0 ignored issues
show
Documentation Bug introduced by
It seems like $cache->get($this->getEntityRulesCacheKey()) of type * is incompatible with the declared type array of property $entityLocalRules.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
131 49
        }
132 49
        if (empty($this->entityLocalRules) || !is_array($this->entityLocalRules)) {
133 15
            $rules = array_merge($this->getGuidRules(), $this->getIdRules(), $this->getCreatedAtRules(), $this->getUpdatedAtRules(), $this->getIpRules());
134 15
            $this->setEntityRules($rules);
135 15
        }
136 49
        return $this->entityLocalRules;
137
    }
138
139
    /**
140
     * Set entity rules.
141
     * @param array $rules
142
     */
143 15
    protected function setEntityRules($rules = [])
144
    {
145 15
        $this->entityLocalRules = $rules;
146 15
        $cache = $this->getCache();
147 15
        if ($cache) {
148 15
            $tagDependency = new \yii\caching\TagDependency(
149 15
                ['tags' => [$this->getEntityRulesCacheTag()]]
150 15
            );
151 15
            $cache->set($this->getEntityRulesCacheKey(), $rules, 0, $tagDependency);
152 15
        }
153 15
    }
154
155
    /**
156
     * Get entity behaviors cache key.
157
     * @return string cache key.
158
     */
159 51
    public function getEntityBehaviorsCacheKey()
160
    {
161 51
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityBehaviors;
162
    }
163
164
    /**
165
     * Get entity behaviors cache tag.
166
     * @return string cache tag.
167
     */
168 15
    public function getEntityBehaviorsCacheTag()
169
    {
170 15
        return static::className() . $this->cachePrefix . static::$cacheTagEntityBehaviors;
171
    }
172
173
    /**
174
     * Get the entity behaviors.
175
     * @return array
176
     */
177 51
    public function getEntityBehaviors()
178
    {
179 51
        $cache = $this->getCache();
180 51
        if ($cache) {
181 51
            $this->entityLocalBehaviors = $cache->get($this->getEntityBehaviorsCacheKey());
0 ignored issues
show
Documentation Bug introduced by
It seems like $cache->get($this->getEntityBehaviorsCacheKey()) of type * is incompatible with the declared type array of property $entityLocalBehaviors.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
182 51
        }
183 51
        if (empty($this->entityLocalBehaviors) || !is_array($this->entityLocalBehaviors)) {
184 15
            $this->setEntityBehaviors($this->getTimestampBehaviors());
185 15
        }
186 51
        return $this->entityLocalBehaviors;
187
    }
188
189
    /**
190
     * Set the entity behaviors.
191
     * @param array $behaviors
192
     */
193 15
    protected function setEntityBehaviors($behaviors)
194
    {
195 15
        $this->entityLocalBehaviors = $behaviors;
196 15
        $cache = $this->getCache();
197 15
        if ($cache) {
198 15
            $tagDependencyConfig = ['tags' => [$this->getEntityBehaviorsCacheTag()]];
199 15
            $tagDependency = new \yii\caching\TagDependency($tagDependencyConfig);
200 15
            $cache->set($this->getEntityBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
201 15
        }
202 15
    }
203
204
    /**
205
     * Reset cache key.
206
     * @param string $cacheKey
207
     * @param mixed $value
208
     * @return boolean whether the value is successfully stored into cache. if
209
     * cache component was not configured, then return false directly.
210
     */
211 1
    public function resetCacheKey($cacheKey, $value = false)
212 1
    {
213
        $cache = $this->getCache();
214
        if ($cache) {
215
            return $this->getCache()->set($cacheKey, $value);
216
        }
217
        return false;
218
    }
219
220
    /**
221
     * Attach events associated with entity model.
222
     */
223 51
    protected function initEntityEvents()
224
    {
225 51
        $this->on(static::EVENT_INIT, [$this, 'onInitCache']);
0 ignored issues
show
Bug introduced by
It seems like on() 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...
226 51
        $this->attachInitGuidEvent(static::$eventNewRecordCreated);
227 51
        $this->attachInitIdEvent(static::$eventNewRecordCreated);
228 51
        $this->attachInitIpEvent(static::$eventNewRecordCreated);
229 51
        if ($this->isNewRecord) {
0 ignored issues
show
Bug introduced by
The property isNewRecord does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
230 51
            $this->trigger(static::$eventNewRecordCreated);
0 ignored issues
show
Bug introduced by
It seems like trigger() 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...
231 51
        }
232 51
        $this->on(static::EVENT_AFTER_FIND, [$this, 'onRemoveExpired']);
0 ignored issues
show
Bug introduced by
It seems like on() 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...
233 51
    }
234
235
    /**
236
     * Initialize the cache prefix.
237
     * @param \yii\base\Event $event
238
     */
239 51
    public function onInitCache($event)
240
    {
241 51
        $sender = $event->sender;
242 51
        $data = $event->data;
243 51
        if (isset($data['prefix'])) {
244
            $sender->cachePrefix = $data['prefix'];
245
        } else {
246 51
            $sender->cachePrefix = $sender::className();
247
        }
248 51
    }
249
250
    /**
251
     * Record warnings.
252
     */
253
    protected function recordWarnings()
254
    {
255
        if (YII_ENV !== YII_ENV_PROD || YII_DEBUG) {
256
            Yii::warning($this->errors);
0 ignored issues
show
Bug introduced by
The property errors does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
257
        }
258
    }
259
260
    /**
261
     * Get guid or id. if neither disabled, return null.
262
     * @return string
263
     */
264 8
    public function __toString()
265
    {
266 8
        if (is_string($this->guidAttribute)) {
267 8
            return $this->guid;
268
        }
269
        if (is_string($this->idAttribute)) {
270
            return $this->id;
271
        }
272
        return null;
273
    }
274
275
    /**
276
     * @inheritdoc
277
     * -------------
278
     * if enable `$idAttribute` and $row[$idAttribute] set, the `idPreassigned`
279
     * will be assigned to true.
280
     */
281 39
    public static function instantiate($row)
282
    {
283 39
        $self = static::buildNoInitModel();
284 39
        if (isset($self->idAttribute) && isset($row[$self->idAttribute])) {
285 39
            $model = new static(['idPreassigned' => true]);
0 ignored issues
show
Unused Code introduced by
The call to EntityTrait::__construct() has too many arguments starting with array('idPreassigned' => true).

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...
286 39
        } else {
287 2
            $model = new static;
288
        }
289 39
        return $model;
290
    }
291
292
    /**
293
     * unset entity attributes.
294
     * @return array result.
295
     */
296
    public function unsetSelfFields()
297
    {
298
        return static::unsetFields($this->attributes, $this->enabledFields());
0 ignored issues
show
Bug introduced by
The property attributes does not seem to exist. Did you mean idAttributeSafe?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
299
    }
300
301
    /**
302
     * unset fields of array.
303
     * @param array $array
304
     * @param array $fields
305
     * @return array
306
     */
307
    public static function unsetFields($array, $fields = null)
308
    {
309
        if (!is_array($array)) {
310
            $fields = [];
311
        }
312
        foreach ($array as $key => $value) {
313
            if (is_string($key) && in_array($key, $fields)) {
314
                unset($array[$key]);
315
            }
316
        }
317
        return $array;
318
    }
319
320
    /**
321
     * Get enabled fields.
322
     * @return string[]
323
     */
324 13
    public function enabledFields()
325
    {
326 13
        return array_merge(
327 13
            is_string($this->guidAttribute) ? [$this->guidAttribute] : [],
328 13
            is_string($this->idAttribute) ? [$this->idAttribute] : [],
329 13
            $this->enabledTimestampFields(),
330 13
            $this->enabledIPFields()
331 13
        );
332
    }
333
}
334