Completed
Push — master ( 9021d7...2fa9a1 )
by vistart
08:17
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
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 48
    public static function buildNoInitModel()
65
    {
66 48
        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 46
    public function rules()
77
    {
78 46
        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 48
    public function behaviors()
89
    {
90 48
        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 48
    protected function getCache()
99
    {
100 48
        $cacheId = $this->cacheId;
101 48
        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 46
    public function getEntityRulesCacheKey()
109
    {
110 46
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityRules;
111
    }
112
113
    /**
114
     * Get entity rules cache tag.
115
     * @return string cache tag.
116
     */
117 12
    public function getEntityRulesCacheTag()
118
    {
119 12
        return static::className() . $this->cachePrefix . static::$cacheTagEntityRules;
120
    }
121
122
    /**
123
     * Get entity rules.
124
     * @return array rules.
125
     */
126 46
    public function getEntityRules()
127
    {
128 46
        $cache = $this->getCache();
129 46
        if ($cache) {
130 46
            $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 46
        }
132 46
        if (empty($this->entityLocalRules) || !is_array($this->entityLocalRules)) {
133 12
            $rules = array_merge($this->getGuidRules(), $this->getIdRules(), $this->getCreatedAtRules(), $this->getUpdatedAtRules(), $this->getIpRules());
134 12
            $this->setEntityRules($rules);
135 12
        }
136 46
        return $this->entityLocalRules;
137
    }
138
139
    /**
140
     * Set entity rules.
141
     * @param array $rules
142
     */
143 12
    protected function setEntityRules($rules = [])
144
    {
145 12
        $this->entityLocalRules = $rules;
146 12
        $cache = $this->getCache();
147 12
        if ($cache) {
148 12
            $tagDependency = new \yii\caching\TagDependency(
149 12
                ['tags' => [$this->getEntityRulesCacheTag()]]
150 12
            );
151 12
            $cache->set($this->getEntityRulesCacheKey(), $rules, 0, $tagDependency);
152 12
        }
153 12
    }
154
155
    /**
156
     * Get entity behaviors cache key.
157
     * @return string cache key.
158
     */
159 48
    public function getEntityBehaviorsCacheKey()
160
    {
161 48
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityBehaviors;
162
    }
163
164
    /**
165
     * Get entity behaviors cache tag.
166
     * @return string cache tag.
167
     */
168 12
    public function getEntityBehaviorsCacheTag()
169
    {
170 12
        return static::className() . $this->cachePrefix . static::$cacheTagEntityBehaviors;
171
    }
172
173
    /**
174
     * Get the entity behaviors.
175
     * @return array
176
     */
177 48
    public function getEntityBehaviors()
178
    {
179 48
        $cache = $this->getCache();
180 48
        if ($cache) {
181 48
            $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 48
        }
183 48
        if (empty($this->entityLocalBehaviors) || !is_array($this->entityLocalBehaviors)) {
184 12
            $this->setEntityBehaviors($this->getTimestampBehaviors());
185 12
        }
186 48
        return $this->entityLocalBehaviors;
187
    }
188
189
    /**
190
     * Set the entity behaviors.
191
     * @param array $behaviors
192
     */
193 12
    protected function setEntityBehaviors($behaviors)
194
    {
195 12
        $this->entityLocalBehaviors = $behaviors;
196 12
        $cache = $this->getCache();
197 12
        if ($cache) {
198 12
            $tagDependencyConfig = ['tags' => [$this->getEntityBehaviorsCacheTag()]];
199 12
            $tagDependency = new \yii\caching\TagDependency($tagDependencyConfig);
200 12
            $cache->set($this->getEntityBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
201 12
        }
202 12
    }
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
    public function resetCacheKey($cacheKey, $value = false)
212
    {
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 48
    protected function initEntityEvents()
224
    {
225 48
        $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 48
        $this->attachInitGuidEvent(static::$eventNewRecordCreated);
227 48
        $this->attachInitIdEvent(static::$eventNewRecordCreated);
228 48
        $this->attachInitIpEvent(static::$eventNewRecordCreated);
229 48
        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 48
            $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 48
        }
232 48
        $this->on(static::EVENT_BEFORE_UPDATE, [$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 48
    }
234
235
    /**
236
     * Initialize the cache prefix.
237
     * @param \yii\base\Event $event
238
     */
239 48
    public function onInitCache($event)
240
    {
241 48
        $sender = $event->sender;
242 48
        $data = $event->data;
243 48
        if (isset($data['prefix'])) {
244
            $sender->cachePrefix = $data['prefix'];
245
        } else {
246 48
            $sender->cachePrefix = $sender::className();
247
        }
248 48
    }
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 35
    public static function instantiate($row)
282
    {
283 35
        $self = static::buildNoInitModel();
284 35
        if (isset($self->idAttribute) && isset($row[$self->idAttribute])) {
285 35
            return 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
        }
287 2
        return new static;
288
    }
289
290
    /**
291
     * unset entity attributes.
292
     * @return array result.
293
     */
294
    public function unsetSelfFields()
295
    {
296
        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...
297
    }
298
299
    /**
300
     * unset fields of array.
301
     * @param array $array
302
     * @param array $fields
303
     * @return array
304
     */
305
    public static function unsetFields($array, $fields = null)
306
    {
307
        if (!is_array($array)) {
308
            $fields = [];
309
        }
310
        foreach ($array as $key => $value) {
311
            if (is_string($key) && in_array($key, $fields)) {
312
                unset($array[$key]);
313
            }
314
        }
315
        return $array;
316
    }
317
318
    /**
319
     * Get enabled fields.
320
     * @return string[]
321
     */
322 12
    public function enabledFields()
323
    {
324 12
        $fields = [];
325 12
        if (is_string($this->guidAttribute)) {
326 5
            $fields[] = $this->guidAttribute;
327 5
        }
328
329 12
        if (is_string($this->idAttribute)) {
330 12
            $fields[] = $this->idAttribute;
331 12
        }
332
333 12
        if (is_string($this->createdAtAttribute)) {
334 12
            $fields[] = $this->createdAtAttribute;
335 12
        }
336
337 12
        if (is_string($this->updatedAtAttribute)) {
338 12
            $fields[] = $this->updatedAtAttribute;
339 12
        }
340 12
        switch ($this->enableIP) {
341 12
            case static::$ipAll:
342 12
                $fields[] = $this->ipTypeAttribute;
343 12
            case static::$ipv6:
344 12
                $fields[] = $this->ipAttribute2;
345 12
                $fields[] = $this->ipAttribute3;
346 12
                $fields[] = $this->ipAttribute4;
347 12
            case static::$ipv4:
348 12
                $fields[] = $this->ipAttribute1;
349 12
            case static::$noIp:
350 12
            default:
351 12
                break;
352 12
        }
353 12
        return $fields;
354
    }
355
}
356