Completed
Push — master ( 1d1fd8...eec31e )
by vistart
05:27
created

EntityTrait::__toString()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 8.125

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
ccs 3
cts 6
cp 0.5
rs 8.8571
cc 5
eloc 6
nc 3
nop 0
crap 8.125
1
<?php
2
3
/**
4
 *   _   __ __ _____ _____ ___  ____  _____
5
 *  | | / // // ___//_  _//   ||  __||_   _|
6
 *  | |/ // /(__  )  / / / /| || |     | |
7
 *  |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 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 108
    public static function buildNoInitModel()
65
    {
66 108
        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 101
    public function rules()
93
    {
94 101
        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 118
    public function behaviors()
105
    {
106 118
        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 118
    protected function getCache()
115
    {
116 118
        $cacheId = $this->cacheId;
117 118
        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 101
    public function getEntityRulesCacheKey()
125
    {
126 101
        return static::class . $this->cachePrefix . static::$cacheKeyEntityRules;
127
    }
128
    
129
    /**
130
     * Get entity rules cache tag.
131
     * @return string cache tag.
132
     */
133 101
    public function getEntityRulesCacheTag()
134
    {
135 101
        return static::class . $this->cachePrefix . static::$cacheTagEntityRules;
136
    }
137
    
138
    /**
139
     * Get entity rules.
140
     * @return array rules.
141
     */
142 101
    public function getEntityRules()
143
    {
144 101
        $cache = $this->getCache();
145 101
        if ($cache) {
146 101
            $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 101
        }
148 101
        if (empty($this->entityLocalRules) || !is_array($this->entityLocalRules)) {
149 101
            $rules = array_merge($this->getGuidRules(), $this->getIdRules(), $this->getCreatedAtRules(), $this->getUpdatedAtRules(), $this->getExpiredAfterRules(), $this->getIpRules());
150 101
            $this->setEntityRules($rules);
151 101
        }
152 101
        return $this->entityLocalRules;
153
    }
154
    
155
    /**
156
     * Set entity rules.
157
     * @param array $rules
158
     */
159 101
    protected function setEntityRules($rules = [])
160
    {
161 101
        $this->entityLocalRules = $rules;
162 101
        $cache = $this->getCache();
163 101
        if ($cache) {
164 101
            $tagDependency = new TagDependency(
165 101
                ['tags' => [$this->getEntityRulesCacheTag()]]
166 101
            );
167 101
            $cache->set($this->getEntityRulesCacheKey(), $rules, 0, $tagDependency);
168 101
        }
169 101
    }
170
    
171
    /**
172
     * Get entity behaviors cache key.
173
     * @return string cache key.
174
     */
175 118
    public function getEntityBehaviorsCacheKey()
176
    {
177 118
        return static::class . $this->cachePrefix . static::$cacheKeyEntityBehaviors;
178
    }
179
    
180
    /**
181
     * Get entity behaviors cache tag.
182
     * @return string cache tag.
183
     */
184 118
    public function getEntityBehaviorsCacheTag()
185
    {
186 118
        return static::class . $this->cachePrefix . static::$cacheTagEntityBehaviors;
187
    }
188
    
189
    /**
190
     * Get the entity behaviors.
191
     * @return array
192
     */
193 118
    public function getEntityBehaviors()
194
    {
195 118
        $cache = $this->getCache();
196 118
        if ($cache) {
197 118
            $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 118
        }
199 118
        if (empty($this->entityLocalBehaviors) || !is_array($this->entityLocalBehaviors)) {
200 118
            $this->setEntityBehaviors($this->getTimestampBehaviors());
201 118
        }
202 118
        return $this->entityLocalBehaviors;
203
    }
204
    
205
    /**
206
     * Set the entity behaviors.
207
     * @param array $behaviors
208
     */
209 118
    protected function setEntityBehaviors($behaviors)
210
    {
211 118
        $this->entityLocalBehaviors = $behaviors;
212 118
        $cache = $this->getCache();
213 118
        if ($cache) {
214 118
            $tagDependencyConfig = ['tags' => [$this->getEntityBehaviorsCacheTag()]];
215 118
            $tagDependency = new TagDependency($tagDependencyConfig);
216 118
            $cache->set($this->getEntityBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
217 118
        }
218 118
    }
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 118
    protected function initEntityEvents()
240
    {
241 118
        $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 118
        $this->attachInitGUIDEvent(static::$eventNewRecordCreated);
243 118
        $this->attachInitIDEvent(static::$eventNewRecordCreated);
244 118
        $this->attachInitIPEvent(static::$eventNewRecordCreated);
245 118
        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 118
            $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 118
        }
248 118
        $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 118
    }
250
    
251
    /**
252
     * Initialize the cache prefix.
253
     * @param ModelEvent $event
254
     */
255 118
    public function onInitCache($event)
256
    {
257 118
        $sender = $event->sender;
258 118
        $data = $event->data;
259 118
        if (isset($data['prefix'])) {
260
            $sender->cachePrefix = $data['prefix'];
261
        } else {
262 118
            $sender->cachePrefix = $sender::className();
263
        }
264 118
    }
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 9
    public function __toString()
281
    {
282 9
        if (is_string($this->guidAttribute) && !empty($this->guidAttribute)) {
283 9
            return $this->getGUID();
284
        }
285
        if (is_string($this->idAttribute) && !empty($this->idAttribute)) {
286
            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 47
    public static function instantiate($row)
298
    {
299 47
        $self = static::buildNoInitModel();
300 47
        if (isset($self->idAttribute) && isset($row[$self->idAttribute])) {
301 47
            $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 47
        } else {
303
            $model = new static;
304
        }
305 47
        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 1
            }
332 1
        }
333 1
        return $array;
334
    }
335
    
336
    /**
337
     * Get enabled fields.
338
     * @return string[]
339
     */
340 4
    public function enabledFields()
341
    {
342 4
        return array_merge(
343 4
            (is_string($this->guidAttribute) && !empty($this->guidAttribute)) ? [$this->guidAttribute] : [],
344 4
            (is_string($this->idAttribute) && !empty($this->idAttribute)) ? [$this->idAttribute] : [],
345 4
            $this->enabledTimestampFields(),
346 4
            $this->enabledIPFields()
347 4
        );
348
    }
349
}
350