Completed
Push — master ( 15c8d0...bf148f )
by vistart
04:55
created

EntityTrait::__toString()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.1158

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 6
cp 0.8333
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 6
nc 3
nop 0
crap 5.1158
1
<?php
2
3
/**
4
 *   _   __ __ _____ _____ ___  ____  _____
5
 *  | | / // // ___//_  _//   ||  __||_   _|
6
 *  | |/ // /(__  )  / / / /| || |     | |
7
 *  |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\base\models\traits;
14
15
use Yii;
16
use yii\base\ModelEvent;
17
use yii\caching\Cache;
18
use yii\caching\TagDependency;
19
20
/**
21
 * This trait must be used in class extended from ActiveRecord. The ActiveRecord
22
 * supports [[\yii\db\ActiveRecord]], [[\yii\mongodb\ActiveRecord]], [[\yii\redis\ActiveRecord]].
23
 * @property array $entityRules
24
 * @property array $entityBehaviors
25
 * @version 1.0
26
 * @author vistart <[email protected]>
27
 */
28
trait EntityTrait
29
{
30
    use GUIDTrait, IDTrait, IPTrait, 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 204
    public static function buildNoInitModel()
65
    {
66 204
        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
     * The classical rules are like following:
75
     * [
76
     *     ['guid', 'required'],
77
     *     ['guid', 'unique'],
78
     *     ['guid', 'string', 'max' => 36],
79
     *
80
     *     ['id', 'required'],
81
     *     ['id', 'unique'],
82
     *     ['id', 'string', 'max' => 4],
83
     *
84
     *     ['created_at', 'safe'],
85
     *     ['updated_at', 'safe'],
86
     *
87
     *     ['ip_type', 'in', 'range' => [4, 6]],
88
     *     ['ip', 'number', 'integerOnly' => true, 'min' => 0],
89
     * ]
90
     * @return array
91
     */
92 195
    public function rules()
93
    {
94 195
        return $this->getEntityRules();
95
    }
96
    
97
    /**
98
     * Populate and return the entity behaviors.
99
     * You should call this function in your extended class and merge the result
100
     * with your behaviors, instead of overriding it, unless you know the
101
     * consequences.
102
     * @return array
103
     */
104 215
    public function behaviors()
105
    {
106 215
        return $this->getEntityBehaviors();
107
    }
108
    
109
    /**
110
     * Get cache component. If cache component is not configured, Yii::$app->cache
111
     * will be given.
112
     * @return Cache cache component.
113
     */
114 215
    protected function getCache()
115
    {
116 215
        $cacheId = $this->cacheId;
117 215
        return empty($cacheId) ? Yii::$app->cache : Yii::$app->$cacheId;
118
    }
119
    
120
    /**
121
     * Get entity rules cache key.
122
     * @return string cache key.
123
     */
124 195
    public function getEntityRulesCacheKey()
125
    {
126 195
        return static::class . $this->cachePrefix . static::$cacheKeyEntityRules;
127
    }
128
    
129
    /**
130
     * Get entity rules cache tag.
131
     * @return string cache tag.
132
     */
133 195
    public function getEntityRulesCacheTag()
134
    {
135 195
        return static::class . $this->cachePrefix . static::$cacheTagEntityRules;
136
    }
137
    
138
    /**
139
     * Get entity rules.
140
     * @return array rules.
141
     */
142 195
    public function getEntityRules()
143
    {
144 195
        $cache = $this->getCache();
145 195
        if ($cache) {
146 195
            $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...
147
        }
148 195
        if (empty($this->entityLocalRules) || !is_array($this->entityLocalRules)) {
149 195
            $rules = array_merge($this->getGuidRules(), $this->getIdRules(), $this->getCreatedAtRules(), $this->getUpdatedAtRules(), $this->getExpiredAfterRules(), $this->getIpRules());
150 195
            $this->setEntityRules($rules);
151
        }
152 195
        return $this->entityLocalRules;
153
    }
154
    
155
    /**
156
     * Set entity rules.
157
     * @param array $rules
158
     */
159 195
    protected function setEntityRules($rules = [])
160
    {
161 195
        $this->entityLocalRules = $rules;
162 195
        $cache = $this->getCache();
163 195
        if ($cache) {
164 195
            $tagDependency = new TagDependency(
165 195
                ['tags' => [$this->getEntityRulesCacheTag()]]
166
            );
167 195
            $cache->set($this->getEntityRulesCacheKey(), $rules, 0, $tagDependency);
168
        }
169 195
    }
170
    
171
    /**
172
     * Get entity behaviors cache key.
173
     * @return string cache key.
174
     */
175 215
    public function getEntityBehaviorsCacheKey()
176
    {
177 215
        return static::class . $this->cachePrefix . static::$cacheKeyEntityBehaviors;
178
    }
179
    
180
    /**
181
     * Get entity behaviors cache tag.
182
     * @return string cache tag.
183
     */
184 215
    public function getEntityBehaviorsCacheTag()
185
    {
186 215
        return static::class . $this->cachePrefix . static::$cacheTagEntityBehaviors;
187
    }
188
    
189
    /**
190
     * Get the entity behaviors.
191
     * @return array
192
     */
193 215
    public function getEntityBehaviors()
194
    {
195 215
        $cache = $this->getCache();
196 215
        if ($cache) {
197 215
            $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...
198
        }
199 215
        if (empty($this->entityLocalBehaviors) || !is_array($this->entityLocalBehaviors)) {
200 215
            $this->setEntityBehaviors($this->getTimestampBehaviors());
201
        }
202 215
        return $this->entityLocalBehaviors;
203
    }
204
    
205
    /**
206
     * Set the entity behaviors.
207
     * @param array $behaviors
208
     */
209 215
    protected function setEntityBehaviors($behaviors)
210
    {
211 215
        $this->entityLocalBehaviors = $behaviors;
212 215
        $cache = $this->getCache();
213 215
        if ($cache) {
214 215
            $tagDependencyConfig = ['tags' => [$this->getEntityBehaviorsCacheTag()]];
215 215
            $tagDependency = new TagDependency($tagDependencyConfig);
216 215
            $cache->set($this->getEntityBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
217
        }
218 215
    }
219
    
220
    /**
221
     * Reset cache key.
222
     * @param string $cacheKey
223
     * @param mixed $value
224
     * @return boolean whether the value is successfully stored into cache. if
225
     * cache component was not configured, then return false directly.
226
     */
227 1
    public function resetCacheKey($cacheKey, $value = false)
228
    {
229 1
        $cache = $this->getCache();
230 1
        if ($cache) {
231 1
            return $this->getCache()->set($cacheKey, $value);
232
        }
233
        return false;
234
    }
235
    
236
    /**
237
     * Attach events associated with entity model.
238
     */
239 215
    protected function initEntityEvents()
240
    {
241 215
        $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...
242 215
        $this->attachInitGUIDEvent(static::$eventNewRecordCreated);
243 215
        $this->attachInitIDEvent(static::$eventNewRecordCreated);
244 215
        $this->attachInitIPEvent(static::$eventNewRecordCreated);
245 215
        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...
246 215
            $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...
247
        }
248 215
        $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...
249 215
    }
250
    
251
    /**
252
     * Initialize the cache prefix.
253
     * @param ModelEvent $event
254
     */
255 215
    public function onInitCache($event)
256
    {
257 215
        $sender = $event->sender;
258 215
        $data = $event->data;
259 215
        if (isset($data['prefix'])) {
260
            $sender->cachePrefix = $data['prefix'];
261
        } else {
262 215
            $sender->cachePrefix = $sender::className();
263
        }
264 215
    }
265
    
266
    /**
267
     * Record warnings.
268
     */
269
    protected function recordWarnings()
270
    {
271
        if (YII_ENV !== YII_ENV_PROD || YII_DEBUG) {
272
            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...
273
        }
274
    }
275
    
276
    /**
277
     * Get guid or id. if neither disabled, return null.
278
     * @return string
279
     */
280 19
    public function __toString()
281
    {
282 19
        if (is_string($this->guidAttribute) && !empty($this->guidAttribute)) {
283 16
            return $this->getGUID();
284
        }
285 3
        if (is_string($this->idAttribute) && !empty($this->idAttribute)) {
286 3
            return $this->getId();
287
        }
288
        return parent::__toString();
289
    }
290
    
291
    /**
292
     * @inheritdoc
293
     * -------------
294
     * if enable `$idAttribute` and $row[$idAttribute] set, the `idPreassigned`
295
     * will be assigned to true.
296
     */
297 92
    public static function instantiate($row)
298
    {
299 92
        $self = static::buildNoInitModel();
300 92
        if (isset($self->idAttribute) && isset($row[$self->idAttribute])) {
301 92
            $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...
302
        } else {
303
            $model = new static;
304
        }
305 92
        return $model;
306
    }
307
    
308
    /**
309
     * unset entity attributes.
310
     * @return array result.
311
     */
312 1
    public function unsetSelfFields()
313
    {
314 1
        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...
315
    }
316
    
317
    /**
318
     * unset fields of array.
319
     * @param array $array
320
     * @param array $fields
321
     * @return array
322
     */
323 1
    public static function unsetFields($array, $fields = null)
324
    {
325 1
        if (!is_array($array)) {
326
            $fields = [];
327
        }
328 1
        foreach ($array as $key => $value) {
329 1
            if (is_string($key) && in_array($key, $fields)) {
330 1
                unset($array[$key]);
331
            }
332
        }
333 1
        return $array;
334
    }
335
    
336
    /**
337
     * Get enabled fields.
338
     * @return string[]
339
     */
340 78
    public function enabledFields()
341
    {
342 78
        return array_merge(
343 78
            (is_string($this->guidAttribute) && !empty($this->guidAttribute)) ? [$this->guidAttribute] : [],
344 78
            (is_string($this->idAttribute) && !empty($this->idAttribute)) ? [$this->idAttribute] : [],
345 78
            $this->enabledTimestampFields(),
346 78
            $this->enabledIPFields()
347
        );
348
    }
349
}
350