Completed
Push — master ( 9b5529...8e3c70 )
by vistart
09:42 queued 03:37
created

EntityTrait::getEntityBehaviorsCacheKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
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
use yii\caching\TagDependency;
17
18
/**
19
 * This trait must be used in class extended from ActiveRecord. The ActiveRecord
20
 * supports \yii\db\ActiveRecord, \yii\mongodb\ActiveRecord, \yii\redis\ActiveRecord.
21
 * @property array $entityRules
22
 * @property array $entityBehaviors
23
 * @version 2.0
24
 * @author vistart <[email protected]>
25
 */
26
trait EntityTrait
27
{
28
    use GUIDTrait,
29
        IDTrait,
30
        IPTrait,
31
        TimestampTrait;
32
33
    private $entityLocalRules = [];
34
    private $entityLocalBehaviors = [];
35
36
    /**
37
     * @var string cache key and tag prefix. the prefix is usually set to full
38
     * qualified class name.
39
     */
40
    public $cachePrefix = '';
41
    public static $eventNewRecordCreated = 'newRecordCreated';
42
    public static $cacheKeyEntityRules = 'entity_rules';
43
    public static $cacheTagEntityRules = 'tag_entity_rules';
44
    public static $cacheKeyEntityBehaviors = 'entity_behaviors';
45
    public static $cacheTagEntityBehaviors = 'tag_entity_behaviors';
46
47
    /**
48
     * @var string cache component id. 
49
     */
50
    public $cacheId = 'cache';
51
52
    /**
53
     * @var boolean Determines to skip initialization.
54
     */
55
    public $skipInit = false;
56
57
    /**
58
     * @var string the name of query class or sub-class.
59
     */
60
    public $queryClass;
61
62
    /**
63
     * @return \static New self without any initializations.
64
     */
65 55
    public static function buildNoInitModel()
66
    {
67 55
        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...
68
    }
69
70
    /**
71
     * Populate and return the entity rules.
72
     * You should call this function in your extended class and merge the result
73
     * with your rules, instead of overriding it, unless you know the
74
     * consequences.
75
     * @return type
76
     */
77 53
    public function rules()
78
    {
79 53
        return $this->getEntityRules();
80
    }
81
82
    /**
83
     * Populate and return the entity behaviors.
84
     * You should call this function in your extended class and merge the result
85
     * with your behaviors, instead of overriding it, unless you know the
86
     * consequences.
87
     * @return type
88
     */
89 55
    public function behaviors()
90
    {
91 55
        return $this->getEntityBehaviors();
92
    }
93
94
    /**
95
     * Get cache component. If cache component is not configured, Yii::$app->cache
96
     * will be given.
97
     * @return \yii\caching\Cache cache component.
98
     */
99 55
    protected function getCache()
100
    {
101 55
        $cacheId = $this->cacheId;
102 55
        return empty($cacheId) ? Yii::$app->cache : Yii::$app->$cacheId;
103
    }
104
105
    /**
106
     * Get entity rules cache key.
107
     * @return string cache key.
108
     */
109 53
    public function getEntityRulesCacheKey()
110
    {
111 53
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityRules;
112
    }
113
114
    /**
115
     * Get entity rules cache tag.
116
     * @return string cache tag.
117
     */
118 17
    public function getEntityRulesCacheTag()
119
    {
120 17
        return static::className() . $this->cachePrefix . static::$cacheTagEntityRules;
121
    }
122
123
    /**
124
     * Get entity rules.
125
     * @return array rules.
126
     */
127 53
    public function getEntityRules()
128
    {
129 53
        $cache = $this->getCache();
130 53
        if ($cache) {
131 53
            $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...
132 53
        }
133 53
        if (empty($this->entityLocalRules) || !is_array($this->entityLocalRules)) {
134 17
            $rules = array_merge($this->getGuidRules(), $this->getIdRules(), $this->getCreatedAtRules(), $this->getUpdatedAtRules(), $this->getIpRules());
135 17
            $this->setEntityRules($rules);
136 17
        }
137 53
        return $this->entityLocalRules;
138
    }
139
140
    /**
141
     * Set entity rules.
142
     * @param array $rules
143
     */
144 17
    protected function setEntityRules($rules = [])
145
    {
146 17
        $this->entityLocalRules = $rules;
147 17
        $cache = $this->getCache();
148 17
        if ($cache) {
149 17
            $tagDependency = new TagDependency(
150 17
                ['tags' => [$this->getEntityRulesCacheTag()]]
151 17
            );
152 17
            $cache->set($this->getEntityRulesCacheKey(), $rules, 0, $tagDependency);
153 17
        }
154 17
    }
155
156
    /**
157
     * Get entity behaviors cache key.
158
     * @return string cache key.
159
     */
160 55
    public function getEntityBehaviorsCacheKey()
161
    {
162 55
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityBehaviors;
163
    }
164
165
    /**
166
     * Get entity behaviors cache tag.
167
     * @return string cache tag.
168
     */
169 17
    public function getEntityBehaviorsCacheTag()
170
    {
171 17
        return static::className() . $this->cachePrefix . static::$cacheTagEntityBehaviors;
172
    }
173
174
    /**
175
     * Get the entity behaviors.
176
     * @return array
177
     */
178 55
    public function getEntityBehaviors()
179
    {
180 55
        $cache = $this->getCache();
181 55
        if ($cache) {
182 55
            $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...
183 55
        }
184 55
        if (empty($this->entityLocalBehaviors) || !is_array($this->entityLocalBehaviors)) {
185 17
            $this->setEntityBehaviors($this->getTimestampBehaviors());
186 17
        }
187 55
        return $this->entityLocalBehaviors;
188
    }
189
190
    /**
191
     * Set the entity behaviors.
192
     * @param array $behaviors
193
     */
194 17
    protected function setEntityBehaviors($behaviors)
195
    {
196 17
        $this->entityLocalBehaviors = $behaviors;
197 17
        $cache = $this->getCache();
198 17
        if ($cache) {
199 17
            $tagDependencyConfig = ['tags' => [$this->getEntityBehaviorsCacheTag()]];
200 17
            $tagDependency = new TagDependency($tagDependencyConfig);
201 17
            $cache->set($this->getEntityBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
202 17
        }
203 17
    }
204
205
    /**
206
     * Reset cache key.
207
     * @param string $cacheKey
208
     * @param mixed $value
209
     * @return boolean whether the value is successfully stored into cache. if
210
     * cache component was not configured, then return false directly.
211
     */
212
    public function resetCacheKey($cacheKey, $value = false)
213
    {
214
        $cache = $this->getCache();
215
        if ($cache) {
216
            return $this->getCache()->set($cacheKey, $value);
217
        }
218
        return false;
219
    }
220
221
    /**
222
     * Attach events associated with entity model.
223
     */
224 55
    protected function initEntityEvents()
225
    {
226 55
        $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...
227 55
        $this->attachInitGuidEvent(static::$eventNewRecordCreated);
228 55
        $this->attachInitIdEvent(static::$eventNewRecordCreated);
229 55
        $this->attachInitIpEvent(static::$eventNewRecordCreated);
230 55
        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...
231 55
            $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...
232 55
        }
233 55
        $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...
234 55
    }
235
236
    /**
237
     * Initialize the cache prefix.
238
     * @param \yii\base\Event $event
239
     */
240 55
    public function onInitCache($event)
241
    {
242 55
        $sender = $event->sender;
243 55
        $data = $event->data;
244 55
        if (isset($data['prefix'])) {
245
            $sender->cachePrefix = $data['prefix'];
246
        } else {
247 55
            $sender->cachePrefix = $sender::className();
248
        }
249 55
    }
250
251
    /**
252
     * Record warnings.
253
     */
254
    protected function recordWarnings()
255
    {
256
        if (YII_ENV !== YII_ENV_PROD || YII_DEBUG) {
257
            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...
258
        }
259
    }
260
261
    /**
262
     * Get guid or id. if neither disabled, return null.
263
     * @return string
264
     */
265 8
    public function __toString()
266
    {
267 8
        if (is_string($this->guidAttribute)) {
268 8
            return $this->guid;
269
        }
270
        if (is_string($this->idAttribute)) {
271
            return $this->id;
272
        }
273
        return null;
274
    }
275
276
    /**
277
     * @inheritdoc
278
     * -------------
279
     * if enable `$idAttribute` and $row[$idAttribute] set, the `idPreassigned`
280
     * will be assigned to true.
281
     */
282 42
    public static function instantiate($row)
283
    {
284 42
        $self = static::buildNoInitModel();
285 42
        if (isset($self->idAttribute) && isset($row[$self->idAttribute])) {
286 42
            $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...
287 42
        } else {
288 2
            $model = new static;
289
        }
290 42
        return $model;
291
    }
292
293
    /**
294
     * unset entity attributes.
295
     * @return array result.
296
     */
297
    public function unsetSelfFields()
298
    {
299
        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...
300
    }
301
302
    /**
303
     * unset fields of array.
304
     * @param array $array
305
     * @param array $fields
306
     * @return array
307
     */
308
    public static function unsetFields($array, $fields = null)
309
    {
310
        if (!is_array($array)) {
311
            $fields = [];
312
        }
313
        foreach ($array as $key => $value) {
314
            if (is_string($key) && in_array($key, $fields)) {
315
                unset($array[$key]);
316
            }
317
        }
318
        return $array;
319
    }
320
321
    /**
322
     * Get enabled fields.
323
     * @return string[]
324
     */
325 16
    public function enabledFields()
326
    {
327 16
        return array_merge(
328 16
            is_string($this->guidAttribute) ? [$this->guidAttribute] : [],
329 16
            is_string($this->idAttribute) ? [$this->idAttribute] : [],
330 16
            $this->enabledTimestampFields(),
331 16
            $this->enabledIPFields()
332 16
        );
333
    }
334
}
335