Completed
Push — master ( 81b65f...3c6407 )
by vistart
07:48
created

BlameableTrait::getBlameableRulesCacheTag()   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 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
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 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 rhosocial\base\helpers\Number;
16
use rhosocial\base\models\queries\BaseUserQuery;
17
use yii\base\InvalidParamException;
18
use yii\base\ModelEvent;
19
use yii\base\NotSupportedException;
20
use yii\behaviors\BlameableBehavior;
21
use yii\caching\TagDependency;
22
use yii\data\Pagination;
23
24
/**
25
 * This trait is used for building blameable model. It contains following features:
26
 * 1.Single-column(field) content;
27
 * 2.Content type;
28
 * 3.Content rules(generated automatically);
29
 * 4.Creator(owner)'s GUID;
30
 * 5.Updater's GUID;
31
 * 6.Confirmation features, provided by [[ConfirmationTrait]];
32
 * 7.Self referenced features, provided by [[SelfBlameableTrait]];
33
 * @property-read array $blameableAttributeRules Get all rules associated with
34
 * blameable.
35
 * @property array $blameableRules Get or set all the rules associated with
36
 * creator, updater, content and its ID, as well as all the inherited rules.
37
 * @property array $blameableBehaviors Get or set all the behaviors assoriated
38
 * with creator and updater, as well as all the inherited behaviors.
39
 * @property-read array $descriptionRules Get description property rules.
40
 * @property-read mixed $content Content.
41
 * @property-read boolean $contentCanBeEdited Whether this content could be edited.
42
 * @property-read array $contentRules Get content rules.
43
 * @property BserUserModel $host The owner of this model.
44
 * @property BaseUserModel $user The owner of this model(the same as $host).
45
 * @property BaseUserModel $updater The updater who updated this model latest.
46
 * @version 1.0
47
 * @author vistart <[email protected]>
48
 */
49
trait BlameableTrait
50
{
51
    use ConfirmationTrait,
52
        SelfBlameableTrait;
53
54
    private $blameableLocalRules = [];
55
    private $blameableLocalBehaviors = [];
56
57
    /**
58
     * @var boolean|string|array Specify the attribute(s) name of content(s). If
59
     * there is only one content attribute, you can assign its name. Or there
60
     * is multiple attributes associated with contents, you can assign their
61
     * names in array. If you don't want to use this feature, please assign
62
     * false.
63
     * For example:
64
     * ```php
65
     * public $contentAttribute = 'comment'; // only one field named as 'comment'.
66
     * ```
67
     * or
68
     * ```php
69
     * public $contentAttribute = ['year', 'month', 'day']; // multiple fields.
70
     * ```
71
     * or
72
     * ```php
73
     * public $contentAttribute = false; // no need of this feature.
74
     * ```
75
     * If you don't need this feature, you should add rules corresponding with
76
     * `content` in `rules()` method of your user model by yourself.
77
     */
78
    public $contentAttribute = 'content';
79
80
    /**
81
     * @var array built-in validator name or validatation method name and
82
     * additional parameters.
83
     */
84
    public $contentAttributeRule = ['string', 'max' => 255];
85
86
    /**
87
     * @var boolean|string Specify the field which stores the type of content.
88
     */
89
    public $contentTypeAttribute = false;
90
91
    /**
92
     * @var boolean|array Specify the logic type of content, not data type. If
93
     * your content doesn't need this feature. please specify false. If the
94
     * $contentAttribute is specified to false, this attribute will be skipped.
95
     * ```php
96
     * public $contentTypes = [
97
     *     'public',
98
     *     'private',
99
     *     'friend',
100
     * ];
101
     * ```
102
     */
103
    public $contentTypes = false;
104
105
    /**
106
     * @var boolean|string This attribute speicfy the name of description
107
     * attribute. If this attribute is assigned to false, this feature will be
108
     * skipped.
109
     */
110
    public $descriptionAttribute = false;
111
112
    /**
113
     * @var string
114
     */
115
    public $initDescription = '';
116
117
    /**
118
     * @var string the attribute that will receive current user ID value. This
119
     * attribute must be assigned.
120
     */
121
    public $createdByAttribute = "user_guid";
122
123
    /**
124
     * @var string the attribute that will receive current user ID value.
125
     * Set this property to false if you do not want to record the updater ID.
126
     */
127
    public $updatedByAttribute = "user_guid";
128
129
    /**
130
     * @var boolean Add combinated unique rule if assigned to true.
131
     */
132
    public $idCreatorCombinatedUnique = true;
133
134
    /**
135
     * @var boolean|string The name of user class which own the current entity.
136
     * If this attribute is assigned to false, this feature will be skipped, and
137
     * when you use create() method of UserTrait, it will be assigned with
138
     * current user class.
139
     */
140
    //public $userClass;
141
    
142
    /**
143
     * @var boolean|string Host class.
144
     */
145
    public $hostClass;
146
    public static $cacheKeyBlameableRules = 'blameable_rules';
147
    public static $cacheTagBlameableRules = 'tag_blameable_rules';
148
    public static $cacheKeyBlameableBehaviors = 'blameable_behaviors';
149
    public static $cacheTagBlameableBehaviors = 'tag_blameable_behaviors';
150
151
    /**
152
     * @inheritdoc
153
     * ------------
154
     * The classical rules is like following:
155
     * [
156
     *     ['guid', 'required'],
157
     *     ['guid', 'unique'],
158
     *     ['guid', 'string', 'max' => 36],
159
     *
160
     *     ['id', 'required'],
161
     *     ['id', 'unique'],
162
     *     ['id', 'string', 'max' => 4],
163
     *
164
     *     ['created_at', 'safe'],
165
     *     ['updated_at', 'safe'],
166
     *
167
     *     ['ip_type', 'in', 'range' => [4, 6]],
168
     *     ['ip', 'number', 'integerOnly' => true, 'min' => 0],
169
     * ]
170
     * @return array
171
     */
172 177
    public function rules()
173
    {
174 177
        return $this->getBlameableRules();
175
    }
176
177
    /**
178
     * @inheritdoc
179
     */
180 184
    public function behaviors()
181
    {
182 184
        return $this->getBlameableBehaviors();
183
    }
184
185
    /**
186
     * Get total of contents which owned by their owner.
187
     * @return integer
188
     */
189 1
    public function countOfOwner()
190
    {
191 1
        $createdByAttribute = $this->createdByAttribute;
192 1
        return static::find()->where([$createdByAttribute => $this->$createdByAttribute])->count();
193
    }
194
195
    /**
196
     * Get content.
197
     * @return mixed
198
     */
199 6
    public function getContent()
200
    {
201 6
        $contentAttribute = $this->contentAttribute;
202 6
        if ($contentAttribute === false) {
203
            return null;
204
        }
205 6
        if (is_array($contentAttribute)) {
206
            $content = [];
207
            foreach ($contentAttribute as $key => $value) {
208
                $content[$key] = $this->$value;
209
            }
210
            return $content;
211
        }
212 6
        return $this->$contentAttribute;
213
    }
214
215
    /**
216
     * Set content.
217
     * @param mixed $content
218
     */
219 60
    public function setContent($content)
220
    {
221 60
        $contentAttribute = $this->contentAttribute;
222 60
        if ($contentAttribute === false) {
223
            return;
224
        }
225 60
        if (is_array($contentAttribute)) {
226
            foreach ($contentAttribute as $key => $value) {
227
                $this->$value = $content[$key];
228
            }
229
            return;
230
        }
231 60
        $this->$contentAttribute = $content;
232 60
    }
233
234
    /**
235
     * Determines whether content could be edited. Your should implement this
236
     * method by yourself.
237
     * @return boolean
238
     * @throws NotSupportedException
239
     */
240
    public function getContentCanBeEdited()
241
    {
242
        if ($this->contentAttribute === false) {
243
            return false;
244
        }
245
        throw new NotSupportedException("This method is not implemented.");
246
    }
247
248
    /**
249
     * Get blameable rules cache key.
250
     * @return string cache key.
251
     */
252 177
    public function getBlameableRulesCacheKey()
253
    {
254 177
        return static::class . $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...
255
    }
256
257
    /**
258
     * Get blameable rules cache tag.
259
     * @return string cache tag
260
     */
261 168
    public function getBlameableRulesCacheTag()
262
    {
263 168
        return static::class . $this->cachePrefix . static::$cacheTagBlameableRules;
264
    }
265
266
    /**
267
     * Get the rules associated with content to be blamed.
268
     * @return array rules.
269
     */
270 177
    public function getBlameableRules()
271
    {
272 177
        $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...
273 177
        if ($cache) {
274 177
            $this->blameableLocalRules = $cache->get($this->getBlameableRulesCacheKey());
275
        }
276
        // 若当前规则不为空,且是数组,则认为是规则数组,直接返回。
277 177
        if (!empty($this->blameableLocalRules) && is_array($this->blameableLocalRules)) {
278 67
            return $this->blameableLocalRules;
279
        }
280
281
        // 父类规则与确认规则合并。
282 168
        if ($cache) {
283 168
            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...
284
        }
285 168
        $rules = array_merge(
286 168
            parent::rules(),
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...
287 168
            $this->getConfirmationRules(),
288 168
            $this->getBlameableAttributeRules(),
289 168
            $this->getDescriptionRules(),
290 168
            $this->getContentRules(),
291 168
            $this->getSelfBlameableRules()
292
        );
293 168
        $this->setBlameableRules($rules);
294 168
        return $this->blameableLocalRules;
295
    }
296
297
    /**
298
     * Get the rules associated with `createdByAttribute`, `updatedByAttribute`
299
     * and `idAttribute`-`createdByAttribute` combination unique.
300
     * @return array rules.
301
     */
302 168
    public function getBlameableAttributeRules()
303
    {
304 168
        $rules = [];
305
        // 创建者和上次修改者由 BlameableBehavior 负责,因此标记为安全。
306 168
        if (!is_string($this->createdByAttribute) || empty($this->createdByAttribute)) {
307
            throw new NotSupportedException('You must assign the creator.');
308
        }
309 168
        $rules[] = [
310 168
            [$this->createdByAttribute],
311 168
            'safe',
312
        ];
313
314 168
        if (is_string($this->updatedByAttribute) && !empty($this->updatedByAttribute)) {
315 106
            $rules[] = [
316 106
                [$this->updatedByAttribute],
317 106
                'safe',
318
            ];
319
        }
320
321 168
        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...
322 167
            $rules ['id'] = [
323 167
                [$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...
324 167
                    $this->createdByAttribute],
325 167
                'unique',
326 167
                '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...
327 167
                    $this->createdByAttribute],
328
            ];
329
        }
330 168
        return $rules;
331
    }
332
333
    /**
334
     * Get the rules associated with `description` attribute.
335
     * @return array rules.
336
     */
337 168
    public function getDescriptionRules()
338
    {
339 168
        $rules = [];
340 168
        if (is_string($this->descriptionAttribute) && !empty($this->descriptionAttribute)) {
341 51
            $rules[] = [
342 51
                [$this->descriptionAttribute],
343 51
                'string'
344
            ];
345 51
            $rules[] = [
346 51
                [$this->descriptionAttribute],
347 51
                'default',
348 51
                'value' => $this->initDescription,
349
            ];
350
        }
351 168
        return $rules;
352
    }
353
354
    /**
355
     * Get the rules associated with `content` and `contentType` attributes.
356
     * @return array rules.
357
     */
358 168
    public function getContentRules()
359
    {
360 168
        if (!$this->contentAttribute) {
361 34
            return [];
362
        }
363 144
        $rules = [];
364 144
        $rules[] = [$this->contentAttribute, 'required'];
365 144
        if ($this->contentAttributeRule) {
366 144
            if (is_string($this->contentAttributeRule)) {
367
                $this->contentAttributeRule = [$this->contentAttributeRule];
368
            }
369 144
            if (is_array($this->contentAttributeRule)) {
370 144
                $rules[] = array_merge([$this->contentAttribute], $this->contentAttributeRule);
371
            }
372
        }
373
374 144
        if (!$this->contentTypeAttribute) {
375 127
            return $rules;
376
        }
377
378 17
        if (is_array($this->contentTypes) && !empty($this->contentTypes)) {
379 17
            $rules[] = [[
380 17
                $this->contentTypeAttribute],
381 17
                'required'];
382 17
            $rules[] = [[
383 17
                $this->contentTypeAttribute],
384 17
                'in',
385 17
                'range' => array_keys($this->contentTypes)];
386
        }
387 17
        return $rules;
388
    }
389
390
    /**
391
     * Set blameable rules.
392
     * @param array $rules
393
     */
394 168
    protected function setBlameableRules($rules = [])
395
    {
396 168
        $this->blameableLocalRules = $rules;
397 168
        $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...
398 168
        if ($cache) {
399 168
            $tagDependency = new TagDependency(['tags' => [$this->getBlameableRulesCacheTag()]]);
400 168
            $cache->set($this->getBlameableRulesCacheKey(), $rules, 0, $tagDependency);
401
        }
402 168
    }
403
404
    /**
405
     * Get blameable behaviors cache key.
406
     * @return string cache key.
407
     */
408 184
    public function getBlameableBehaviorsCacheKey()
409
    {
410 184
        return static::class . $this->cachePrefix . static::$cacheKeyBlameableBehaviors;
411
    }
412
413
    /**
414
     * Get blameable behaviors cache tag.
415
     * @return string cache tag.
416
     */
417 173
    public function getBlameableBehaviorsCacheTag()
418
    {
419 173
        return static::class . $this->cachePrefix . static::$cacheTagBlameableBehaviors;
420
    }
421
422
    /**
423
     * Get blameable behaviors. If current behaviors array is empty, the init
424
     * array will be given.
425
     * @return array
426
     */
427 184
    public function getBlameableBehaviors()
428
    {
429 184
        $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...
430 184
        if ($cache) {
431 184
            $this->blameableLocalBehaviors = $cache->get($this->getBlameableBehaviorsCacheKey());
432
        }
433 184
        if (empty($this->blameableLocalBehaviors) || !is_array($this->blameableLocalBehaviors)) {
434 173
            if ($cache) {
435 173
                TagDependency::invalidate($cache, [$this->getEntityBehaviorsCacheTag()]);
0 ignored issues
show
Bug introduced by
The method getEntityBehaviorsCacheTag() does not exist on rhosocial\base\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...
436
            }
437 173
            $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...
438 173
            $behaviors['blameable'] = [
439 173
                'class' => BlameableBehavior::class,
440 173
                'createdByAttribute' => $this->createdByAttribute,
441 173
                'updatedByAttribute' => $this->updatedByAttribute,
442 173
                'value' => [$this,
443 173
                    'onGetCurrentUserGuid'],
444
            ];
445 173
            $this->setBlameableBehaviors($behaviors);
446
        }
447 184
        return $this->blameableLocalBehaviors;
448
    }
449
450
    /**
451
     * Set blameable behaviors.
452
     * @param array $behaviors
453
     */
454 173
    protected function setBlameableBehaviors($behaviors = [])
455
    {
456 173
        $this->blameableLocalBehaviors = $behaviors;
457 173
        $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...
458 173
        if ($cache) {
459 173
            $tagDependencyConfig = ['tags' => [$this->getBlameableBehaviorsCacheTag()]];
460 173
            $tagDependency = new TagDependency($tagDependencyConfig);
461 173
            $cache->set($this->getBlameableBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
462
        }
463 173
    }
464
465
    /**
466
     * Set description.
467
     * @return string description.
468
     */
469 1
    public function getDescription()
470
    {
471 1
        $descAttribute = $this->descriptionAttribute;
472 1
        return is_string($descAttribute) ? $this->$descAttribute : null;
473
    }
474
475
    /**
476
     * Get description.
477
     * @param string $desc description.
478
     * @return string|null description if enabled, or null if disabled.
479
     */
480 1
    public function setDescription($desc)
481
    {
482 1
        $descAttribute = $this->descriptionAttribute;
483 1
        return is_string($descAttribute) ? $this->$descAttribute = $desc : null;
484
    }
485
486
    /**
487
     * Get blame who owned this blameable model.
488
     * NOTICE! This method will not check whether `$hostClass` exists. You should
489
     * specify it in `init()` method.
490
     * @return BaseUserQuery user.
491
     */
492 17
    public function getUser()
493
    {
494 17
        return $this->getHost();
495
    }
496
497
    /**
498
     * Declares a `has-one` relation.
499
     * The declaration is returned in terms of a relational [[\yii\db\ActiveQuery]] instance
500
     * through which the related record can be queried and retrieved back.
501
     *
502
     * A `has-one` relation means that there is at most one related record matching
503
     * the criteria set by this relation, e.g., a customer has one country.
504
     *
505
     * For example, to declare the `country` relation for `Customer` class, we can write
506
     * the following code in the `Customer` class:
507
     *
508
     * ```php
509
     * public function getCountry()
510
     * {
511
     *     return $this->hasOne(Country::className(), ['id' => 'country_id']);
512
     * }
513
     * ```
514
     *
515
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
516
     * in the related class `Country`, while the 'country_id' value refers to an attribute name
517
     * in the current AR class.
518
     *
519
     * Call methods declared in [[\yii\db\ActiveQuery]] to further customize the relation.
520
     *
521
     * This method is provided by [[\yii\db\BaseActiveRecord]].
522
     * @param string $class the class name of the related record
523
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
524
     * the attributes of the record associated with the `$class` model, while the values of the
525
     * array refer to the corresponding attributes in **this** AR class.
526
     * @return \yii\dbActiveQueryInterface the relational query object.
527
     */
528
    public abstract function hasOne($class, $link);
529
    
530
    /**
531
     * Get host of this model.
532
     * @return BaseUserQuery
533
     */
534 32
    public function getHost()
535
    {
536 32
        $hostClass = $this->hostClass;
537 32
        $model = $hostClass::buildNoInitModel();
538 32
        return $this->hasOne($hostClass::className(), [$model->guidAttribute => $this->createdByAttribute]);
539
    }
540
    
541
    /**
542
     * Set host of this model.
543
     * @param string $host
544
     * @return type
545
     */
546 139
    public function setHost($host)
547
    {
548 139
        if ($host instanceof $this->hostClass || $host instanceof \yii\web\IdentityInterface) {
549 103
            return $this->{$this->createdByAttribute} = $host->getGUID();
550
        }
551 46
        if (is_string($host) && preg_match(Number::GUID_REGEX, $host)) {
552
            return $this->{$this->createdByAttribute} = Number::guid_bin($host);
553
        }
554 46
        if (strlen($host) == 16) {
555 46
            return $this->{$this->createdByAttribute} = $host;
556
        }
557
        return false;
558
    }
559
    
560
    /**
561
     *
562
     * @param BaseUserModel|string $user
563
     * @return boolean
564
     */
565 4
    public function setUser($user)
566
    {
567 4
        return $this->setHost($user);
568
    }
569
570
    /**
571
     * Get updater who updated this blameable model recently.
572
     * NOTICE! This method will not check whether `$hostClass` exists. You should
573
     * specify it in `init()` method.
574
     * @return BaseUserQuery user.
575
     */
576 6
    public function getUpdater()
577
    {
578 6
        if (!is_string($this->updatedByAttribute) || empty($this->updatedByAttribute)) {
579 1
            return null;
580
        }
581 5
        $hostClass = $this->hostClass;
582 5
        $model = $hostClass::buildNoInitModel();
583
        /* @var $model BaseUserModel */
584 5
        return $this->hasOne($hostClass::className(), [$model->guidAttribute => $this->updatedByAttribute]);
585
    }
586
    
587
    /**
588
     *
589
     * @param BaseUserModel|string $user
0 ignored issues
show
Bug introduced by
There is no parameter named $user. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
590
     * @return boolean
591
     */
592 5
    public function setUpdater($updater)
593
    {
594 5
        if (!is_string($this->updatedByAttribute) || empty($this->updatedByAttribute)) {
595 1
            return false;
596
        }
597 4
        if ($updater instanceof $this->hostClass || $updater instanceof \yii\web\IdentityInterface) {
598 1
            return $this->{$this->updatedByAttribute} = $updater->getGUID();
599
        }
600 3
        if (is_string($updater) && preg_match(Number::GUID_REGEX, $updater)) {
601 1
            return $this->{$this->updatedByAttribute} = Number::guid_bin($updater);
602
        }
603 2
        if (strlen($updater) == 16) {
604 1
            return $this->{$this->updatedByAttribute} = $updater;
605
        }
606 1
        return false;
607
    }
608
609
    /**
610
     * This event is triggered before the model update.
611
     * This method is ONLY used for being triggered by event. DO NOT call,
612
     * override or modify it directly, unless you know the consequences.
613
     * @param ModelEvent $event
614
     */
615 54
    public function onContentChanged($event)
616
    {
617 54
        $sender = $event->sender;
618
        /* @var $sender static */
619 54
        return $sender->resetConfirmation();
620
    }
621
622
    /**
623
     * Return the current user's GUID if current model doesn't specify the owner
624
     * yet, or return the owner's GUID if current model has been specified.
625
     * This method is ONLY used for being triggered by event. DO NOT call,
626
     * override or modify it directly, unless you know the consequences.
627
     * @param ModelEvent $event
628
     * @return string the GUID of current user or the owner.
629
     */
630 133
    public function onGetCurrentUserGuid($event)
631
    {
632 133
        $sender = $event->sender;
633
        /* @var $sender static */
634 133
        if (isset($sender->attributes[$sender->createdByAttribute])) {
635 133
            return $sender->attributes[$sender->createdByAttribute];
0 ignored issues
show
Bug introduced by
The property attributes 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...
636
        }
637
        $identity = \Yii::$app->user->identity;
638
        /* @var $identity BaseUserModel */
639
        if ($identity) {
640
            return $identity->getGUID();
641
        }
642
    }
643
644
    /**
645
     * Initialize type of content. the first of element[index is 0] of
646
     * $contentTypes will be used.
647
     * @param ModelEvent $event
648
     */
649 20
    public function onInitContentType($event)
650
    {
651 20
        $sender = $event->sender;
652
        /* @var $sender static */
653 20
        if (!is_string($sender->contentTypeAttribute) || empty($sender->contentTypeAttribute)) {
654
            return;
655
        }
656 20
        $contentTypeAttribute = $sender->contentTypeAttribute;
657 20
        if (!isset($sender->$contentTypeAttribute) &&
658 20
            !empty($sender->contentTypes) &&
659 20
            is_array($sender->contentTypes)) {
660 20
            $sender->$contentTypeAttribute = $sender->contentTypes[0];
661
        }
662 20
    }
663
664
    /**
665
     * Initialize description property with $initDescription.
666
     * @param ModelEvent $event
667
     */
668 66
    public function onInitDescription($event)
669
    {
670 66
        $sender = $event->sender;
671
        /* @var $sender static */
672 66
        if (!is_string($sender->descriptionAttribute) || empty($sender->descriptionAttribute)) {
673
            return;
674
        }
675 66
        $descriptionAttribute = $sender->descriptionAttribute;
676 66
        if (empty($sender->$descriptionAttribute)) {
677 66
            $sender->$descriptionAttribute = $sender->initDescription;
678
        }
679 66
    }
680
681
    /**
682
     * Attaches an event handler to an event.
683
     *
684
     * The event handler must be a valid PHP callback. The following are
685
     * some examples:
686
     *
687
     * ```
688
     * function ($event) { ... }         // anonymous function
689
     * [$object, 'handleClick']          // $object->handleClick()
690
     * ['Page', 'handleClick']           // Page::handleClick()
691
     * 'handleClick'                     // global function handleClick()
692
     * ```
693
     *
694
     * The event handler must be defined with the following signature,
695
     *
696
     * ```
697
     * function ($event)
698
     * ```
699
     *
700
     * where `$event` is an [[Event]] object which includes parameters associated with the event.
701
     *
702
     * This method is provided by [[\yii\base\Component]].
703
     * @param string $name the event name
704
     * @param callable $handler the event handler
705
     * @param mixed $data the data to be passed to the event handler when the event is triggered.
706
     * When the event handler is invoked, this data can be accessed via [[Event::data]].
707
     * @param boolean $append whether to append new event handler to the end of the existing
708
     * handler list. If false, the new handler will be inserted at the beginning of the existing
709
     * handler list.
710
     * @see off()
711
     */
712
    public abstract function on($name, $handler, $data = null, $append = true);
713
714
    /**
715
     * Detaches an existing event handler from this component.
716
     * This method is the opposite of [[on()]].
717
     * This method is provided by [[\yii\base\Component]]
718
     * @param string $name event name
719
     * @param callable $handler the event handler to be removed.
720
     * If it is null, all handlers attached to the named event will be removed.
721
     * @return boolean if a handler is found and detached
722
     * @see on()
723
     */
724
    public abstract function off($name, $handler = null);
725
726
    /**
727
     * Attach events associated with blameable model.
728
     */
729 184
    public function initBlameableEvents()
730
    {
731 184
        $this->on(static::$eventConfirmationChanged, [$this, "onConfirmationChanged"]);
732 184
        $this->on(static::$eventNewRecordCreated, [$this, "onInitConfirmation"]);
733 184
        $contentTypeAttribute = $this->contentTypeAttribute;
734 184
        if (is_string($contentTypeAttribute) && !empty($contentTypeAttribute) && !isset($this->$contentTypeAttribute)) {
735 20
            $this->on(static::$eventNewRecordCreated, [$this, "onInitContentType"]);
736
        }
737 184
        $descriptionAttribute = $this->descriptionAttribute;
738 184
        if (is_string($descriptionAttribute) && !empty($descriptionAttribute) && !isset($this->$descriptionAttribute)) {
739 66
            $this->on(static::$eventNewRecordCreated, [$this, 'onInitDescription']);
740
        }
741 184
        $this->on(static::EVENT_BEFORE_UPDATE, [$this, "onContentChanged"]);
742 184
        $this->initSelfBlameableEvents();
743 184
    }
744
745
    /**
746
     * @inheritdoc
747
     */
748 71
    public function enabledFields()
749
    {
750 71
        $fields = parent::enabledFields();
751 71
        if (is_string($this->createdByAttribute) && !empty($this->createdByAttribute)) {
752 71
            $fields[] = $this->createdByAttribute;
753
        }
754 71
        if (is_string($this->updatedByAttribute) && !empty($this->updatedByAttribute) &&
755 71
            $this->createdByAttribute != $this->updatedByAttribute) {
756
            $fields[] = $this->updatedByAttribute;
757
        }
758 71
        if (is_string($this->contentAttribute)) {
759 71
            $fields[] = $this->contentAttribute;
760
        }
761 71
        if (is_array($this->contentAttribute)) {
762
            $fields = array_merge($fields, $this->contentAttribute);
763
        }
764 71
        if (is_string($this->descriptionAttribute)) {
765 1
            $fields[] = $this->descriptionAttribute;
766
        }
767 71
        if (is_string($this->confirmationAttribute)) {
768 1
            $fields[] = $this->confirmationAttribute;
769
        }
770 71
        if (is_string($this->parentAttribute)) {
771
            $fields[] = $this->parentAttribute;
772
        }
773 71
        return $fields;
774
    }
775
776
    /**
777
     * Find all follows by specified identity. If `$identity` is null, the logged-in
778
     * identity will be taken.
779
     * @param string|integer $pageSize If it is 'all`, then will find all follows,
780
     * the `$currentPage` parameter will be skipped. If it is integer, it will be
781
     * regarded as sum of models in one page.
782
     * @param integer $currentPage The current page number, begun with 0.
783
     * @param {$this->hostClass} $identity
0 ignored issues
show
Documentation introduced by
The doc-type {$this->hostClass} could not be parsed: Unknown type name "{$this-" 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...
784
     * @return static[] If no follows, null will be given, or return follow array.
785
     */
786 1
    public static function findAllByIdentityInBatch($pageSize = 'all', $currentPage = 0, $identity = null)
787
    {
788 1
        if ($pageSize === 'all') {
789 1
            return static::findByIdentity($identity)->all();
790
        }
791 1
        return static::findByIdentity($identity)->page($pageSize, $currentPage)->all();
792
    }
793
794
    /**
795
     * Find one follow by specified identity. If `$identity` is null, the logged-in
796
     * identity will be taken. If $identity doesn't has the follower, null will
797
     * be given.
798
     * @param integer $id user id.
799
     * @param boolean $throwException
800
     * @param {$this->hostClass} $identity
0 ignored issues
show
Documentation introduced by
The doc-type {$this->hostClass} could not be parsed: Unknown type name "{$this-" 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...
801
     * @return static
802
     * @throws InvalidParamException
803
     */
804 1
    public static function findOneById($id, $throwException = true, $identity = null)
805
    {
806 1
        $query = static::findByIdentity($identity);
807 1
        if (!empty($id)) {
808 1
            $query = $query->id($id);
809
        }
810 1
        $model = $query->one();
811 1
        if (!$model && $throwException) {
812 1
            throw new InvalidParamException('Model Not Found.');
813
        }
814 1
        return $model;
815
    }
816
817
    /**
818
     * Get total of follows of specified identity.
819
     * @param {$this->hostClass} $identity
0 ignored issues
show
Documentation introduced by
The doc-type {$this->hostClass} could not be parsed: Unknown type name "{$this-" 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...
820
     * @return integer total.
821
     */
822 2
    public static function countByIdentity($identity = null)
823
    {
824 2
        return (int)(static::findByIdentity($identity)->count());
825
    }
826
827
    /**
828
     * Get pagination, used for building contents page by page.
829
     * @param integer $limit
830
     * @param {$this->hostClass} $identity
0 ignored issues
show
Documentation introduced by
The doc-type {$this->hostClass} could not be parsed: Unknown type name "{$this-" 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...
831
     * @return Pagination
832
     */
833 1
    public static function getPagination($limit = 10, $identity = null)
834
    {
835 1
        $limit = (int) $limit;
836 1
        $count = static::countByIdentity($identity);
837 1
        if ($limit > $count) {
838 1
            $limit = $count;
839
        }
840 1
        return new Pagination(['totalCount' => $count, 'pageSize' => $limit]);
841
    }
842
}
843