Completed
Push — master ( 7fc3f3...dbb6f1 )
by vistart
05:17
created

EntityTrait::behaviors()   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 4
Bugs 0 Features 0
Metric Value
c 4
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 36
    public static function buildNoInitModel()
65
    {
66 36
        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 34
    public function rules()
77
    {
78 34
        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 36
    public function behaviors()
89
    {
90 36
        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 36
    protected function getCache()
99
    {
100 36
        $cacheId = $this->cacheId;
101 36
        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 34
    public function getEntityRulesCacheKey()
109
    {
110 34
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityRules;
111
    }
112
113
    /**
114
     * Get entity rules cache tag.
115
     * @return string cache tag.
116
     */
117 8
    public function getEntityRulesCacheTag()
118
    {
119 8
        return static::className() . $this->cachePrefix . static::$cacheTagEntityRules;
120
    }
121
122
    /**
123
     * Get entity rules.
124
     * @return array rules.
125
     */
126 34
    public function getEntityRules()
127
    {
128 34
        $cache = $this->getCache();
129 34
        if ($cache) {
130 34
            $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 34
        }
132 34
        if (empty($this->entityLocalRules) || !is_array($this->entityLocalRules)) {
133 8
            $rules = array_merge($this->getGuidRules(), $this->getIdRules(), $this->getCreatedAtRules(), $this->getUpdatedAtRules(), $this->getIpRules());
134 8
            $this->setEntityRules($rules);
135 8
        }
136 34
        return $this->entityLocalRules;
137
    }
138
139
    /**
140
     * Set entity rules.
141
     * @param array $rules
142
     */
143 8
    protected function setEntityRules($rules = [])
144
    {
145 8
        $this->entityLocalRules = $rules;
146 8
        $cache = $this->getCache();
147 8
        if ($cache) {
148 8
            $tagDependency = new \yii\caching\TagDependency(
149 8
                ['tags' => [$this->getEntityRulesCacheTag()]]
150 8
            );
151 8
            $cache->set($this->getEntityRulesCacheKey(), $rules, 0, $tagDependency);
152 8
        }
153 8
    }
154
155
    /**
156
     * Get entity behaviors cache key.
157
     * @return string cache key.
158
     */
159 36
    public function getEntityBehaviorsCacheKey()
160
    {
161 36
        return static::className() . $this->cachePrefix . static::$cacheKeyEntityBehaviors;
162
    }
163
164
    /**
165
     * Get entity behaviors cache tag.
166
     * @return string cache tag.
167
     */
168 8
    public function getEntityBehaviorsCacheTag()
169
    {
170 8
        return static::className() . $this->cachePrefix . static::$cacheTagEntityBehaviors;
171
    }
172
173
    /**
174
     * Get the entity behaviors.
175
     * @return array
176
     */
177 36
    public function getEntityBehaviors()
178
    {
179 36
        $cache = $this->getCache();
180 36
        if ($cache) {
181 36
            $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 36
        }
183 36
        if (empty($this->entityLocalBehaviors) || !is_array($this->entityLocalBehaviors)) {
184 8
            $this->setEntityBehaviors($this->getTimestampBehaviors());
185 8
        }
186 36
        return $this->entityLocalBehaviors;
187
    }
188
189
    /**
190
     * Set the entity behaviors.
191
     * @param array $behaviors
192
     */
193 8
    protected function setEntityBehaviors($behaviors)
194
    {
195 8
        $this->entityLocalBehaviors = $behaviors;
196 8
        $cache = $this->getCache();
197 8
        if ($cache) {
198 8
            $tagDependencyConfig = ['tags' => [$this->getEntityBehaviorsCacheTag()]];
199 8
            $tagDependency = new \yii\caching\TagDependency($tagDependencyConfig);
200 8
            $cache->set($this->getEntityBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
201 8
        }
202 8
    }
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 36
    protected function initEntityEvents()
224
    {
225 36
        $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 36
        $this->attachInitGuidEvent(static::$eventNewRecordCreated);
227 36
        $this->attachInitIdEvent(static::$eventNewRecordCreated);
228 36
        $this->attachInitIpEvent(static::$eventNewRecordCreated);
229 36
        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 36
            $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 36
        }
232 36
    }
233
234
    /**
235
     * Initialize the cache prefix.
236
     * @param \yii\base\Event $event
237
     */
238 36
    public function onInitCache($event)
239
    {
240 36
        $sender = $event->sender;
241 36
        $data = $event->data;
242 36
        if (isset($data['prefix'])) {
243
            $sender->cachePrefix = $data['prefix'];
244
        } else {
245 36
            $sender->cachePrefix = $sender::className();
246
        }
247 36
    }
248
249
    /**
250
     * Record warnings.
251
     */
252
    protected function recordWarnings()
253
    {
254
        if (YII_ENV !== YII_ENV_PROD || YII_DEBUG) {
255
            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...
256
        }
257
    }
258
259
    /**
260
     * Get guid or id. if neither disabled, return null.
261
     * @return string
262
     */
263 7
    public function __toString()
264
    {
265 7
        if (is_string($this->guidAttribute)) {
266 7
            return $this->guid;
267
        }
268
        if (is_string($this->idAttribute)) {
269
            return $this->id;
270
        }
271
        return null;
272
    }
273
274
    /**
275
     * @inheritdoc
276
     * -------------
277
     * if enable `$idAttribute` and $row[$idAttribute] set, the `idPreassigned`
278
     * will be assigned to true.
279
     */
280 27
    public static function instantiate($row)
281
    {
282 27
        $self = static::buildNoInitModel();
283 27
        if (isset($self->idAttribute) && isset($row[$self->idAttribute])) {
284 19
            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...
285
        }
286 8
        return new static;
287
    }
288
289
    /**
290
     * unset entity attributes.
291
     * @return array result.
292
     */
293
    public function unsetSelfFields()
294
    {
295
        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...
296
    }
297
298
    /**
299
     * unset fields of array.
300
     * @param array $array
301
     * @param array $fields
302
     * @return array
303
     */
304
    public static function unsetFields($array, $fields = null)
305
    {
306
        if (!is_array($array)) {
307
            $fields = [];
308
        }
309
        foreach ($array as $key => $value) {
310
            if (is_string($key) && in_array($key, $fields)) {
311
                unset($array[$key]);
312
            }
313
        }
314
        return $array;
315
    }
316
317
    /**
318
     * Get enabled fields.
319
     * @return array
320
     */
321 2
    public function enabledFields()
322
    {
323 2
        $fields = [];
324 2
        if (is_string($this->guidAttribute)) {
325 1
            $fields[] = $this->guidAttribute;
326 1
        }
327
328 2
        if (is_string($this->idAttribute)) {
329 2
            $fields[] = $this->idAttribute;
330 2
        }
331
332 2
        if (is_string($this->createdAtAttribute)) {
333 2
            $fields[] = $this->createdAtAttribute;
334 2
        }
335
336 2
        if (is_string($this->updatedAtAttribute)) {
337 2
            $fields[] = $this->updatedAtAttribute;
338 2
        }
339 2
        switch ($this->enableIP) {
340 2
            case static::$ipAll:
341 2
                $fields[] = $this->ipTypeAttribute;
342 2
            case static::$ipv6:
343 2
                $fields[] = $this->ipAttribute2;
344 2
                $fields[] = $this->ipAttribute3;
345 2
                $fields[] = $this->ipAttribute4;
346 2
            case static::$ipv4:
347 2
                $fields[] = $this->ipAttribute1;
348 2
            case static::$noIp:
349 2
            default:
350 2
                break;
351 2
        }
352 2
        return $fields;
353
    }
354
}
355