Completed
Push — master ( ac64bc...0be11e )
by vistart
07:19
created

BlameableTrait::hasEverEdited()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 9
ccs 0
cts 6
cp 0
rs 9.6666
cc 3
eloc 6
nc 2
nop 0
crap 12
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license https://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
use yii\base\InvalidParamException;
16
use yii\behaviors\BlameableBehavior;
17
use yii\caching\TagDependency;
18
use yii\data\Pagination;
19
20
/**
21
 * This trait is used for building blameable model. It contains following features:
22
 * 1.单列内容;多列内容待定;
23
 * 2.内容类型;具体类型应当自定义;
24
 * 3.内容规则;自动生成;
25
 * 4.归属用户 GUID;
26
 * 5.创建用户 GUID;
27
 * 6.上次更新用户 GUID;
28
 * 7.Confirmation features, provided by [[ConfirmationTrait]];
29
 * @property-read array $blameableAttributeRules Get all rules associated with
30
 * blameable.
31
 * @property array $blameableRules Get or set all the rules associated with
32
 * creator, updater, content and its ID, as well as all the inherited rules.
33
 * @property array $blameableBehaviors Get or set all the behaviors assoriated
34
 * with creator and updater, as well as all the inherited behaviors.
35
 * @property-read array $descriptionRules Get description property rules.
36
 * @property-read mixed $content Content.
37
 * @property-read boolean $contentCanBeEdited Whether this content could be edited.
38
 * @property-read array $contentRules Get content rules.
39
 * @property-read \vistart\Models\models\BaseUserModel $user
40
 * @property-read \vistart\Models\models\BaseUserModel $updater
41
 * @version 2.0
42
 * @author vistart <[email protected]>
43
 */
44
trait BlameableTrait
45
{
46
    use ConfirmationTrait,
47
        SelfBlameableTrait;
48
49
    private $blameableLocalRules = [];
50
    private $blameableLocalBehaviors = [];
51
52
    /**
53
     * @var boolean|string|array Specify the attribute(s) name of content(s). If
54
     * there is only one content attribute, you can assign its name. Or there
55
     * is multiple attributes associated with contents, you can assign their
56
     * names in array. If you don't want to use this feature, please assign
57
     * false.
58
     * For example:
59
     * ```php
60
     * public $contentAttribute = 'comment'; // only one field named as 'comment'.
61
     * ```
62
     * or
63
     * ```php
64
     * public $contentAttribute = ['year', 'month', 'day']; // multiple fields.
65
     * ```
66
     * or
67
     * ```php
68
     * public $contentAttribute = false; // no need of this feature.
69
     * ```
70
     * If you don't need this feature, you should add rules corresponding with
71
     * `content` in `rules()` method of your user model by yourself.
72
     */
73
    public $contentAttribute = 'content';
74
75
    /**
76
     * @var array built-in validator name or validatation method name and
77
     * additional parameters.
78
     */
79
    public $contentAttributeRule = ['string', 'max' => 255];
80
81
    /**
82
     * @var boolean|string Specify the field which stores the type of content.
83
     */
84
    public $contentTypeAttribute = false;
85
86
    /**
87
     * @var boolean|array Specify the logic type of content, not data type. If
88
     * your content doesn't need this feature. please specify false. If the
89
     * $contentAttribute is specified to false, this attribute will be skipped.
90
     * ```php
91
     * public $contentTypes = [
92
     *     'public',
93
     *     'private',
94
     *     'friend',
95
     * ];
96
     * ```
97
     */
98
    public $contentTypes = false;
99
100
    /**
101
     * @var boolean|string This attribute speicfy the name of description
102
     * attribute. If this attribute is assigned to false, this feature will be
103
     * skipped.
104
     */
105
    public $descriptionAttribute = false;
106
107
    /**
108
     * @var string
109
     */
110
    public $initDescription = '';
111
112
    /**
113
     * @var string the attribute that will receive current user ID value. This
114
     * attribute must be assigned.
115
     */
116
    public $createdByAttribute = "user_guid";
117
118
    /**
119
     * @var string the attribute that will receive current user ID value.
120
     * Set this property to false if you do not want to record the updater ID.
121
     */
122
    public $updatedByAttribute = "user_guid";
123
124
    /**
125
     * @var boolean Add combinated unique rule if assigned to true.
126
     */
127
    public $idCreatorCombinatedUnique = true;
128
129
    /**
130
     * @var boolean|string The name of user class which own the current entity.
131
     * If this attribute is assigned to false, this feature will be skipped, and
132
     * when you use create() method of UserTrait, it will be assigned with
133
     * current user class.
134
     */
135
    public $userClass;
136
    public static $cacheKeyBlameableRules = 'blameable_rules';
137
    public static $cacheTagBlameableRules = 'tag_blameable_rules';
138
    public static $cacheKeyBlameableBehaviors = 'blameable_behaviors';
139
    public static $cacheTagBlameableBehaviors = 'tag_blameable_behaviors';
140
141
    /**
142
     * @inheritdoc
143
     */
144 37
    public function rules()
145
    {
146 37
        return $this->getBlameableRules();
147
    }
148
149
    /**
150
     * @inheritdoc
151
     */
152 37
    public function behaviors()
153
    {
154 37
        return $this->getBlameableBehaviors();
155
    }
156
157
    /**
158
     * Get total of contents which owned by their owner.
159
     * @return integer
160
     */
161 2
    public function countOfOwner()
162
    {
163 2
        $createdByAttribute = $this->createdByAttribute;
164 2
        return static::find()->where([$createdByAttribute => $this->$createdByAttribute])->count();
165
    }
166
167
    /**
168
     * Get content.
169
     * @return mixed
170
     */
171
    public function getContent()
172
    {
173
        $contentAttribute = $this->contentAttribute;
174
        if ($contentAttribute === false) {
175
            return null;
176
        }
177
        if (is_array($contentAttribute)) {
178
            $content = [];
179
            foreach ($contentAttribute as $key => $value) {
180
                $content[$key] = $this->$value;
181
            }
182
            return $content;
183
        }
184
        return $this->$contentAttribute;
185
    }
186
187
    /**
188
     * Set content.
189
     * @param mixed $content
190
     */
191
    public function setContent($content)
192
    {
193
        $contentAttribute = $this->contentAttribute;
194
        if ($contentAttribute === false) {
195
            return;
196
        }
197
        if (is_array($contentAttribute)) {
198
            foreach ($contentAttribute as $key => $value) {
199
                $this->$value = $content[$key];
200
            }
201
            return;
202
        }
203
        $this->$contentAttribute = $content;
204
    }
205
206
    /**
207
     * Determines whether content could be edited. Your should implement this
208
     * method by yourself.
209
     * @return boolean
210
     * @throws \yii\base\NotSupportedException
211
     */
212
    public function getContentCanBeEdited()
213
    {
214
        if ($this->contentAttribute === false) {
215
            return false;
216
        }
217
        throw new \yii\base\NotSupportedException("This method is not implemented.");
218
    }
219
220
    /**
221
     * Check it has been ever edited.
222
     * @return boolean Whether this content has ever been edited.
223
     */
224
    public function hasEverEdited()
225
    {
226
        $createdAtAttribute = $this->createdByAttribute;
227
        $updatedAtAttribute = $this->updatedByAttribute;
228
        if (!$createdAtAttribute || !$updatedAtAttribute) {
229
            return false;
230
        }
231
        return $this->$createdAtAttribute === $this->$updatedAtAttribute;
232
    }
233
234
    /**
235
     * Get blameable rules cache key.
236
     * @return string cache key.
237
     */
238 37
    public function getBlameableRulesCacheKey()
239
    {
240 37
        return static::className() . $this->cachePrefix . static::$cacheKeyBlameableRules;
0 ignored issues
show
Bug introduced by
The property cachePrefix 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...
241
    }
242
243
    /**
244
     * Get blameable rules cache tag.
245
     * @return string cache tag
246
     */
247 13
    public function getBlameableRulesCacheTag()
248
    {
249 13
        return static::className() . $this->cachePrefix . static::$cacheTagBlameableRules;
250
    }
251
252
    /**
253
     * Get the rules associated with content to be blamed.
254
     * @return array rules.
255
     */
256 37
    public function getBlameableRules()
257
    {
258 37
        $cache = $this->getCache();
0 ignored issues
show
Bug introduced by
It seems like getCache() 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...
259 37
        if ($cache) {
260 37
            $this->blameableLocalRules = $cache->get($this->getBlameableRulesCacheKey());
261 37
        }
262
        // 若当前规则不为空,且是数组,则认为是规则数组,直接返回。
263 37
        if (!empty($this->blameableLocalRules) && is_array($this->blameableLocalRules)) {
264 30
            return $this->blameableLocalRules;
265
        }
266
267
        // 父类规则与确认规则合并。
268 13
        if ($cache) {
269 13
            TagDependency::invalidate($cache, [$this->getEntityRulesCacheTag()]);
0 ignored issues
show
Bug introduced by
It seems like getEntityRulesCacheTag() 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...
270 13
        }
271 13
        $rules = array_merge(
272 13
            parent::rules(), $this->getConfirmationRules(), $this->getBlameableAttributeRules(), $this->getDescriptionRules(), $this->getContentRules(), $this->getSelfBlameableRules()
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (rules() instead of getBlameableRules()). Are you sure this is correct? If so, you might want to change this to $this->rules().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
273 13
        );
274 13
        $this->setBlameableRules($rules);
275 13
        return $this->blameableLocalRules;
276
    }
277
278
    /**
279
     * Get the rules associated with `createdByAttribute`, `updatedByAttribute`
280
     * and `idAttribute`-`createdByAttribute` combination unique.
281
     * @return array rules.
282
     */
283 13
    public function getBlameableAttributeRules()
284
    {
285 13
        $rules = [];
286
        // 创建者和上次修改者由 BlameableBehavior 负责,因此标记为安全。
287 13
        if (!is_string($this->createdByAttribute) || empty($this->createdByAttribute)) {
288
            throw new \yii\base\NotSupportedException('You must assign the creator.');
289
        }
290 13
        $rules[] = [
291 13
            [$this->createdByAttribute],
292 13
            'safe',
293
        ];
294
295 13
        if (is_string($this->updatedByAttribute) && !empty($this->updatedByAttribute)) {
296 3
            $rules[] = [
297 3
                [$this->updatedByAttribute],
298 3
                'safe',
299
            ];
300 3
        }
301
302 13
        if ($this->idCreatorCombinatedUnique && is_string($this->idAttribute)) {
0 ignored issues
show
Bug introduced by
The property idAttribute does not seem to exist. Did you mean refIdAttribute?

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...
303 12
            $rules [] = [
304 12
                [$this->idAttribute,
0 ignored issues
show
Bug introduced by
The property idAttribute does not seem to exist. Did you mean refIdAttribute?

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...
305 12
                    $this->createdByAttribute],
306 12
                'unique',
307 12
                'targetAttribute' => [$this->idAttribute,
0 ignored issues
show
Bug introduced by
The property idAttribute does not seem to exist. Did you mean refIdAttribute?

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...
308 12
                    $this->createdByAttribute],
309
            ];
310 12
        }
311 13
        return $rules;
312
    }
313
314
    /**
315
     * Get the rules associated with `description` attribute.
316
     * @return array rules.
317
     */
318 13
    public function getDescriptionRules()
319
    {
320 13
        $rules = [];
321 13
        if (is_string($this->descriptionAttribute) && !empty($this->descriptionAttribute)) {
322 1
            $rules[] = [
323 1
                [$this->descriptionAttribute],
324
                'string'
325 1
            ];
326 1
            $rules[] = [
327 1
                [$this->descriptionAttribute],
328 1
                'default',
329 1
                'value' => $this->initDescription,
330
            ];
331 1
        }
332 13
        return $rules;
333
    }
334
335
    /**
336
     * Get the rules associated with `content` and `contentType` attributes.
337
     * @return array rules.
338
     */
339 13
    public function getContentRules()
340
    {
341 13
        if (!$this->contentAttribute) {
342 2
            return [];
343
        }
344 11
        $rules = [];
345 11
        $rules[] = [[
346 11
            $this->contentAttribute],
347 11
            'required'];
348 11
        if ($this->contentAttributeRule) {
349 11
            if (is_string($this->contentAttributeRule)) {
350
                $this->contentAttributeRule = [$this->contentAttributeRule];
351
            }
352 11
            if (is_array($this->contentAttributeRule)) {
353 11
                $rules[] = array_merge([$this->contentAttribute], $this->contentAttributeRule);
354 11
            }
355 11
        }
356
357 11
        if (!$this->contentTypeAttribute) {
358 9
            return $rules;
359
        }
360
361 2
        if (is_array($this->contentTypes) && !empty($this->contentTypes)) {
362 2
            $rules[] = [[
363 2
                $this->contentTypeAttribute],
364 2
                'required'];
365 2
            $rules[] = [[
366 2
                $this->contentTypeAttribute],
367 2
                'in',
368 2
                'range' => array_keys($this->contentTypes)];
369 2
        }
370 2
        return $rules;
371
    }
372
373
    /**
374
     * Set blameable rules.
375
     * @param array $rules
376
     */
377 13
    protected function setBlameableRules($rules = [])
378
    {
379 13
        $this->blameableLocalRules = $rules;
380 13
        $cache = $this->getCache();
0 ignored issues
show
Bug introduced by
It seems like getCache() 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...
381 13
        if ($cache) {
382 13
            $tagDependency = new \yii\caching\TagDependency(['tags' => [$this->getBlameableRulesCacheTag()]]);
383 13
            $cache->set($this->getBlameableRulesCacheKey(), $rules, 0, $tagDependency);
384 13
        }
385 13
    }
386
387
    /**
388
     * Get blameable behaviors cache key.
389
     * @return string cache key.
390
     */
391 37
    public function getBlameableBehaviorsCacheKey()
392
    {
393 37
        return static::className() . $this->cachePrefix . static::$cacheKeyBlameableBehaviors;
394
    }
395
396
    /**
397
     * Get blameable behaviors cache tag.
398
     * @return string cache tag.
399
     */
400 13
    public function getBlameableBehaviorsCacheTag()
401
    {
402 13
        return static::className() . $this->cachePrefix . static::$cacheTagBlameableBehaviors;
403
    }
404
405
    /**
406
     * Get blameable behaviors. If current behaviors array is empty, the init
407
     * array will be given.
408
     * @return array
409
     */
410 37
    public function getBlameableBehaviors()
411
    {
412 37
        $cache = $this->getCache();
0 ignored issues
show
Bug introduced by
It seems like getCache() 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...
413 37
        if ($cache) {
414 37
            $this->blameableLocalBehaviors = $cache->get($this->getBlameableBehaviorsCacheKey());
415 37
        }
416 37
        if (empty($this->blameableLocalBehaviors) || !is_array($this->blameableLocalBehaviors)) {
417 13
            if ($cache) {
418 13
                TagDependency::invalidate($cache, [$this->getEntityBehaviorsCacheTag()]);
0 ignored issues
show
Bug introduced by
The method getEntityBehaviorsCacheTag() does not exist on vistart\Models\traits\BlameableTrait. Did you maybe mean behaviors()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
419 13
            }
420 13
            $behaviors = parent::behaviors();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (behaviors() instead of getBlameableBehaviors()). Are you sure this is correct? If so, you might want to change this to $this->behaviors().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
421 13
            $behaviors['blameable'] = [
422 13
                'class' => BlameableBehavior::className(),
423 13
                'createdByAttribute' => $this->createdByAttribute,
424 13
                'updatedByAttribute' => $this->updatedByAttribute,
425 13
                'value' => [$this,
426 13
                    'onGetCurrentUserGuid'],
427
            ];
428 13
            $this->setBlameableBehaviors($behaviors);
429 13
        }
430 37
        return $this->blameableLocalBehaviors;
431
    }
432
433
    /**
434
     * Set blameable behaviors.
435
     * @param array $behaviors
436
     */
437 13
    protected function setBlameableBehaviors($behaviors = [])
438
    {
439 13
        $this->blameableLocalBehaviors = $behaviors;
440 13
        $cache = $this->getCache();
0 ignored issues
show
Bug introduced by
It seems like getCache() 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...
441 13
        if ($cache) {
442 13
            $tagDependencyConfig = ['tags' => [$this->getBlameableBehaviorsCacheTag()]];
443 13
            $tagDependency = new \yii\caching\TagDependency($tagDependencyConfig);
444 13
            $cache->set($this->getBlameableBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
445 13
        }
446 13
    }
447
448
    /**
449
     * Set description.
450
     * @return string description.
451
     */
452
    public function getDescription()
453
    {
454
        $descAttribute = $this->descriptionAttribute;
455
        return is_string($descAttribute) ? $this->$descAttribute : null;
456
    }
457
458
    /**
459
     * Get description.
460
     * @param string $desc description.
461
     * @return string|null description if enabled, or null if disabled.
462
     */
463
    public function setDescription($desc)
464
    {
465
        $descAttribute = $this->descriptionAttribute;
466
        return is_string($descAttribute) ? $this->$descAttribute = $desc : null;
467
    }
468
469
    /**
470
     * Get blame who owned this blameable model.
471
     * NOTICE! This method will not check whether `$userClass` exists. You should
472
     * specify it in `init()` method.
473
     * @return \vistart\Models\queries\BaseUserQuery user.
474
     */
475 1
    public function getUser()
476
    {
477 1
        $userClass = $this->userClass;
478 1
        $model = $userClass::buildNoInitModel();
479 1
        return $this->hasOne($userClass::className(), [$model->guidAttribute => $this->createdByAttribute]);
0 ignored issues
show
Bug introduced by
It seems like hasOne() 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...
480
    }
481
482
    /**
483
     * Get updater who updated this blameable model recently.
484
     * NOTICE! This method will not check whether `$userClass` exists. You should
485
     * specify it in `init()` method.
486
     * @return \vistart\Models\queries\BaseUserQuery user.
487
     */
488 1
    public function getUpdater()
489
    {
490 1
        if (!is_string($this->updatedByAttribute)) {
491 1
            return null;
492
        }
493
        $userClass = $this->userClass;
494
        $model = $userClass::buildNoInitModel();
495
        return $this->hasOne($userClass::className(), [$model->guidAttribute => $this->updatedByAttribute]);
0 ignored issues
show
Bug introduced by
It seems like hasOne() 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...
496
    }
497
498
    /**
499
     * This event is triggered before the model update.
500
     * This method is ONLY used for being triggered by event. DO NOT call,
501
     * override or modify it directly, unless you know the consequences.
502
     * @param \yii\base\Event $event
503
     */
504 11
    public function onContentChanged($event)
505
    {
506 11
        $sender = $event->sender;
507 11
        $sender->resetConfirmation();
508 11
    }
509
510
    /**
511
     * Return the current user's GUID if current model doesn't specify the owner
512
     * yet, or return the owner's GUID if current model has been specified.
513
     * This method is ONLY used for being triggered by event. DO NOT call,
514
     * override or modify it directly, unless you know the consequences.
515
     * @param \yii\base\Event $event
516
     * @return string the GUID of current user or the owner.
517
     */
518 37
    public function onGetCurrentUserGuid($event)
519
    {
520 37
        $sender = $event->sender;
521 37
        if (isset($sender->attributes[$sender->createdByAttribute])) {
522 37
            return $sender->attributes[$sender->createdByAttribute];
523
        }
524
        $identity = \Yii::$app->user->identity;
525
        if ($identity) {
526
            $igAttribute = $identity->guidAttribute;
527
            return $identity->$igAttribute;
528
        }
529
    }
530
531
    /**
532
     * Initialize type of content. the first of element[index is 0] of
533
     * $contentTypes will be used.
534
     * @param \yii\base\Event $event
535
     */
536 36
    public function onInitContentType($event)
537
    {
538 36
        $sender = $event->sender;
539 36
        if (!isset($sender->contentTypeAttribute) || !is_string($sender->contentTypeAttribute)) {
540 29
            return;
541
        }
542 7
        $contentTypeAttribute = $sender->contentTypeAttribute;
543 7
        if (!isset($sender->$contentTypeAttribute) &&
544 7
            !empty($sender->contentTypes) &&
545 7
            is_array($sender->contentTypes)) {
546 7
            $sender->$contentTypeAttribute = $sender->contentTypes[0];
547 7
        }
548 7
    }
549
550
    /**
551
     * Initialize description property with $initDescription.
552
     * @param \yii\base\Event $event
553
     */
554 37
    public function onInitDescription($event)
555
    {
556 37
        $sender = $event->sender;
557 37
        if (!isset($sender->descriptionAttribute) || !is_string($sender->descriptionAttribute)) {
558 31
            return;
559
        }
560 6
        $descriptionAttribute = $sender->descriptionAttribute;
561 6
        if (empty($sender->$descriptionAttribute)) {
562 6
            $sender->$descriptionAttribute = $sender->initDescription;
563 6
        }
564 6
    }
565
566
    /**
567
     * Attach events associated with blameable model.
568
     */
569 37
    public function initBlameableEvents()
570
    {
571 37
        $this->on(static::$eventConfirmationChanged, [$this, "onConfirmationChanged"]);
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...
572 37
        $this->on(static::$eventNewRecordCreated, [$this, "onInitConfirmation"]);
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...
573 37
        $contentTypeAttribute = $this->contentTypeAttribute;
574 37
        if (!isset($this->$contentTypeAttribute)) {
575 36
            $this->on(static::$eventNewRecordCreated, [$this, "onInitContentType"]);
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...
576 36
        }
577 37
        $descriptionAttribute = $this->descriptionAttribute;
578 37
        if (!isset($this->$descriptionAttribute)) {
579 37
            $this->on(static::$eventNewRecordCreated, [$this, 'onInitDescription']);
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...
580 37
        }
581 37
        $this->on(static::EVENT_BEFORE_UPDATE, [$this, "onContentChanged"]);
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...
582 37
        $this->initSelfBlameableEvents();
583 37
    }
584
585
    /**
586
     * @inheritdoc
587
     */
588 11
    public function enabledFields()
589
    {
590 11
        $fields = parent::enabledFields();
591 11
        if (is_string($this->createdByAttribute)) {
592 11
            $fields[] = $this->createdByAttribute;
593 11
        }
594 11
        if (is_string($this->updatedByAttribute)) {
595 2
            $fields[] = $this->updatedByAttribute;
596 2
        }
597 11
        if (is_string($this->contentAttribute)) {
598 11
            $fields[] = $this->contentAttribute;
599 11
        }
600 11
        if (is_array($this->contentAttribute)) {
601
            $fields = array_merge($fields, $this->contentAttribute);
602
        }
603 11
        if (is_string($this->descriptionAttribute)) {
604
            $fields[] = $this->descriptionAttribute;
605
        }
606 11
        if (is_string($this->confirmationAttribute)) {
607
            $fields[] = $this->confirmationAttribute;
608
        }
609 11
        if (is_string($this->parentAttribute)) {
610
            $fields[] = $this->parentAttribute;
611
        }
612 11
        return $fields;
613
    }
614
615
    /**
616
     * Find all follows by specified identity. If `$identity` is null, the logged-in
617
     * identity will be taken.
618
     * @param string|integer $pageSize If it is 'all`, then will find all follows,
619
     * the `$currentPage` parameter will be skipped. If it is integer, it will be
620
     * regarded as sum of models in one page.
621
     * @param integer $currentPage The current page number, begun with 0.
622
     * @param $userClass $identity
0 ignored issues
show
Documentation introduced by
The doc-type $userClass could not be parsed: Unknown type name "$userClass" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
623
     * @return static[] If no follows, null will be given, or return follow array.
624
     */
625
    public static function findAllByIdentityInBatch($pageSize = 'all', $currentPage = 0, $identity = null)
626
    {
627
        if ($pageSize === 'all') {
628
            return static::findByIdentity($identity)->all();
629
        }
630
        return static::findByIdentity($identity)->page($currentPage, $pageSize)->all();
631
    }
632
633
    /**
634
     * Find one follow by specified identity. If `$identity` is null, the logged-in
635
     * identity will be taken. If $identity doesn't has the follower, null will
636
     * be given.
637
     * @param integer $id user id.
638
     * @param boolean $throwException
639
     * @param $userClass $identity
0 ignored issues
show
Documentation introduced by
The doc-type $userClass could not be parsed: Unknown type name "$userClass" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
640
     * @return static
641
     * @throws NotFoundHttpException
642
     */
643
    public static function findOneById($id, $throwException = true, $identity = null)
644
    {
645
        $query = static::findByIdentity($identity);
646
        if (!empty($id)) {
647
            $query = $query->id($id);
648
        }
649
        $model = $query->one();
650
        if (!$model && $throwException) {
651
            throw new InvalidParamException('Model Not Found.');
652
        }
653
        return $model;
654
    }
655
656
    /**
657
     * Get total of follows of specified identity.
658
     * @param $userClass $identity
0 ignored issues
show
Documentation introduced by
The doc-type $userClass could not be parsed: Unknown type name "$userClass" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
659
     * @return integer total.
660
     */
661
    public static function countByIdentity($identity = null)
662
    {
663
        return static::findByIdentity($identity)->count();
664
    }
665
666
    /**
667
     * Get pagination, used for building contents page by page.
668
     * @param integer $limit
669
     * @param $userClass $identity
0 ignored issues
show
Documentation introduced by
The doc-type $userClass could not be parsed: Unknown type name "$userClass" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
670
     * @return Pagination
671
     */
672
    public static function getPagination($limit = 10, $identity = null)
673
    {
674
        $limit = (int) $limit;
675
        $count = static::countByIdentity($identity);
676
        if ($limit > $count) {
677
            $limit = $count;
678
        }
679
        return new Pagination(['totalCount' => $count, 'pageSize' => $limit]);
680
    }
681
}
682