Completed
Push — master ( aa4e61...eb8d71 )
by vistart
09:43
created

BlameableTrait::findOneById()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 3
crap 4
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 197
    public function rules()
173
    {
174 197
        return $this->getBlameableRules();
175
    }
176
177
    /**
178
     * @inheritdoc
179
     */
180 204
    public function behaviors()
181
    {
182 204
        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 63
    public function setContent($content)
220
    {
221 63
        $contentAttribute = $this->contentAttribute;
222 63
        if ($contentAttribute === false) {
223
            return;
224
        }
225 63
        if (is_array($contentAttribute)) {
226
            foreach ($contentAttribute as $key => $value) {
227
                $this->$value = $content[$key];
228
            }
229
            return;
230
        }
231 63
        $this->$contentAttribute = $content;
232 63
    }
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 197
    public function getBlameableRulesCacheKey()
253
    {
254 197
        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 197
    public function getBlameableRulesCacheTag()
262
    {
263 197
        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 197
    public function getBlameableRules()
271
    {
272 197
        $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 197
        if ($cache) {
274 197
            $this->blameableLocalRules = $cache->get($this->getBlameableRulesCacheKey());
275
        }
276
        // 若当前规则不为空,且是数组,则认为是规则数组,直接返回。
277 197
        if (!empty($this->blameableLocalRules) && is_array($this->blameableLocalRules)) {
278 79
            return $this->blameableLocalRules;
279
        }
280
281
        // 父类规则与确认规则合并。
282 197
        if ($cache) {
283 197
            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 197
        $rules = array_merge(
286 197
            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 197
            $this->getConfirmationRules(),
288 197
            $this->getBlameableAttributeRules(),
289 197
            $this->getDescriptionRules(),
290 197
            $this->getContentRules(),
291 197
            $this->getSelfBlameableRules()
292
        );
293 197
        $this->setBlameableRules($rules);
294 197
        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 197
    public function getBlameableAttributeRules()
303
    {
304 197
        $rules = [];
305
        // 创建者和上次修改者由 BlameableBehavior 负责,因此标记为安全。
306 197
        if (!is_string($this->createdByAttribute) || empty($this->createdByAttribute)) {
307
            throw new NotSupportedException('You must assign the creator.');
308
        }
309 197
        $rules[] = [
310 197
            [$this->createdByAttribute],
311 197
            'safe',
312
        ];
313
314 197
        if (is_string($this->updatedByAttribute) && !empty($this->updatedByAttribute)) {
315 111
            $rules[] = [
316 111
                [$this->updatedByAttribute],
317 111
                'safe',
318
            ];
319
        }
320
321 197
        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 195
            $rules ['id'] = [
323 195
                [$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 195
                    $this->createdByAttribute],
325 195
                'unique',
326 195
                '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 195
                    $this->createdByAttribute],
328
            ];
329
        }
330 197
        return $rules;
331
    }
332
    
333 197
    public function getIdRules()
334
    {
335 197
        if ($this->idCreatorCombinatedUnique && $this->idAttributeType !== static::$idTypeAutoIncrement) {
0 ignored issues
show
Bug introduced by
The property idAttributeType 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...
336
            return [
337 138
                [[$this->idAttribute], 'required'],
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...
338
            ];
339
        }
340 105
        return parent::getIdRules();
341
    }
342
343
    /**
344
     * Get the rules associated with `description` attribute.
345
     * @return array rules.
346
     */
347 197
    public function getDescriptionRules()
348
    {
349 197
        $rules = [];
350 197
        if (is_string($this->descriptionAttribute) && !empty($this->descriptionAttribute)) {
351 65
            $rules[] = [
352 65
                [$this->descriptionAttribute],
353 65
                'string'
354
            ];
355 65
            $rules[] = [
356 65
                [$this->descriptionAttribute],
357 65
                'default',
358 65
                'value' => $this->initDescription,
359
            ];
360
        }
361 197
        return $rules;
362
    }
363
364
    /**
365
     * Get the rules associated with `content` and `contentType` attributes.
366
     * @return array rules.
367
     */
368 197
    public function getContentRules()
369
    {
370 197
        if (!$this->contentAttribute) {
371 46
            return [];
372
        }
373 161
        $rules = [];
374 161
        $rules[] = [$this->contentAttribute, 'required'];
375 161
        if ($this->contentAttributeRule) {
376 161
            if (is_string($this->contentAttributeRule)) {
377
                $this->contentAttributeRule = [$this->contentAttributeRule];
378
            }
379 161
            if (is_array($this->contentAttributeRule)) {
380 161
                $rules[] = array_merge([$this->contentAttribute], $this->contentAttributeRule);
381
            }
382
        }
383
384 161
        if (!$this->contentTypeAttribute) {
385 142
            return $rules;
386
        }
387
388 19
        if (is_array($this->contentTypes) && !empty($this->contentTypes)) {
389 19
            $rules[] = [[
390 19
                $this->contentTypeAttribute],
391 19
                'required'];
392 19
            $rules[] = [[
393 19
                $this->contentTypeAttribute],
394 19
                'in',
395 19
                'range' => array_keys($this->contentTypes)];
396
        }
397 19
        return $rules;
398
    }
399
400
    /**
401
     * Set blameable rules.
402
     * @param array $rules
403
     */
404 197
    protected function setBlameableRules($rules = [])
405
    {
406 197
        $this->blameableLocalRules = $rules;
407 197
        $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...
408 197
        if ($cache) {
409 197
            $tagDependency = new TagDependency(['tags' => [$this->getBlameableRulesCacheTag()]]);
410 197
            $cache->set($this->getBlameableRulesCacheKey(), $rules, 0, $tagDependency);
411
        }
412 197
    }
413
414
    /**
415
     * Get blameable behaviors cache key.
416
     * @return string cache key.
417
     */
418 204
    public function getBlameableBehaviorsCacheKey()
419
    {
420 204
        return static::class . $this->cachePrefix . static::$cacheKeyBlameableBehaviors;
421
    }
422
423
    /**
424
     * Get blameable behaviors cache tag.
425
     * @return string cache tag.
426
     */
427 204
    public function getBlameableBehaviorsCacheTag()
428
    {
429 204
        return static::class . $this->cachePrefix . static::$cacheTagBlameableBehaviors;
430
    }
431
432
    /**
433
     * Get blameable behaviors. If current behaviors array is empty, the init
434
     * array will be given.
435
     * @return array
436
     */
437 204
    public function getBlameableBehaviors()
438
    {
439 204
        $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...
440 204
        if ($cache) {
441 204
            $this->blameableLocalBehaviors = $cache->get($this->getBlameableBehaviorsCacheKey());
442
        }
443 204
        if (empty($this->blameableLocalBehaviors) || !is_array($this->blameableLocalBehaviors)) {
444 204
            if ($cache) {
445 204
                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...
446
            }
447 204
            $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...
448 204
            $behaviors['blameable'] = [
449 204
                'class' => BlameableBehavior::class,
450 204
                'createdByAttribute' => $this->createdByAttribute,
451 204
                'updatedByAttribute' => $this->updatedByAttribute,
452 204
                'value' => [$this,
453 204
                    'onGetCurrentUserGuid'],
454
            ];
455 204
            $this->setBlameableBehaviors($behaviors);
456
        }
457 204
        return $this->blameableLocalBehaviors;
458
    }
459
460
    /**
461
     * Set blameable behaviors.
462
     * @param array $behaviors
463
     */
464 204
    protected function setBlameableBehaviors($behaviors = [])
465
    {
466 204
        $this->blameableLocalBehaviors = $behaviors;
467 204
        $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...
468 204
        if ($cache) {
469 204
            $tagDependencyConfig = ['tags' => [$this->getBlameableBehaviorsCacheTag()]];
470 204
            $tagDependency = new TagDependency($tagDependencyConfig);
471 204
            $cache->set($this->getBlameableBehaviorsCacheKey(), $behaviors, 0, $tagDependency);
472
        }
473 204
    }
474
475
    /**
476
     * Set description.
477
     * @return string description.
478
     */
479 1
    public function getDescription()
480
    {
481 1
        $descAttribute = $this->descriptionAttribute;
482 1
        return is_string($descAttribute) ? $this->$descAttribute : null;
483
    }
484
485
    /**
486
     * Get description.
487
     * @param string $desc description.
488
     * @return string|null description if enabled, or null if disabled.
489
     */
490 1
    public function setDescription($desc)
491
    {
492 1
        $descAttribute = $this->descriptionAttribute;
493 1
        return is_string($descAttribute) ? $this->$descAttribute = $desc : null;
494
    }
495
496
    /**
497
     * Get blame who owned this blameable model.
498
     * NOTICE! This method will not check whether `$hostClass` exists. You should
499
     * specify it in `init()` method.
500
     * @return BaseUserQuery user.
501
     */
502 17
    public function getUser()
503
    {
504 17
        return $this->getHost();
505
    }
506
507
    /**
508
     * Declares a `has-one` relation.
509
     * The declaration is returned in terms of a relational [[\yii\db\ActiveQuery]] instance
510
     * through which the related record can be queried and retrieved back.
511
     *
512
     * A `has-one` relation means that there is at most one related record matching
513
     * the criteria set by this relation, e.g., a customer has one country.
514
     *
515
     * For example, to declare the `country` relation for `Customer` class, we can write
516
     * the following code in the `Customer` class:
517
     *
518
     * ```php
519
     * public function getCountry()
520
     * {
521
     *     return $this->hasOne(Country::className(), ['id' => 'country_id']);
522
     * }
523
     * ```
524
     *
525
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
526
     * in the related class `Country`, while the 'country_id' value refers to an attribute name
527
     * in the current AR class.
528
     *
529
     * Call methods declared in [[\yii\db\ActiveQuery]] to further customize the relation.
530
     *
531
     * This method is provided by [[\yii\db\BaseActiveRecord]].
532
     * @param string $class the class name of the related record
533
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
534
     * the attributes of the record associated with the `$class` model, while the values of the
535
     * array refer to the corresponding attributes in **this** AR class.
536
     * @return \yii\dbActiveQueryInterface the relational query object.
537
     */
538
    public abstract function hasOne($class, $link);
539
    
540
    /**
541
     * Get host of this model.
542
     * @return BaseUserQuery
543
     */
544 34
    public function getHost()
545
    {
546 34
        $hostClass = $this->hostClass;
547 34
        $model = $hostClass::buildNoInitModel();
548 34
        return $this->hasOne($hostClass::className(), [$model->guidAttribute => $this->createdByAttribute]);
549
    }
550
    
551
    /**
552
     * Set host of this model.
553
     * @param string $host
554
     * @return type
555
     */
556 146
    public function setHost($host)
557
    {
558 146
        if ($host instanceof $this->hostClass || $host instanceof \yii\web\IdentityInterface) {
559 107
            return $this->{$this->createdByAttribute} = $host->getGUID();
560
        }
561 50
        if (is_string($host) && preg_match(Number::GUID_REGEX, $host)) {
562 1
            return $this->{$this->createdByAttribute} = Number::guid_bin($host);
563
        }
564 50
        if (strlen($host) == 16) {
565 49
            return $this->{$this->createdByAttribute} = $host;
566
        }
567 1
        return false;
568
    }
569
    
570
    /**
571
     *
572
     * @param BaseUserModel|string $user
573
     * @return boolean
574
     */
575 4
    public function setUser($user)
576
    {
577 4
        return $this->setHost($user);
578
    }
579
580
    /**
581
     * Get updater who updated this blameable model recently.
582
     * NOTICE! This method will not check whether `$hostClass` exists. You should
583
     * specify it in `init()` method.
584
     * @return BaseUserQuery user.
585
     */
586 6
    public function getUpdater()
587
    {
588 6
        if (!is_string($this->updatedByAttribute) || empty($this->updatedByAttribute)) {
589 1
            return null;
590
        }
591 5
        $hostClass = $this->hostClass;
592 5
        $model = $hostClass::buildNoInitModel();
593
        /* @var $model BaseUserModel */
594 5
        return $this->hasOne($hostClass::className(), [$model->guidAttribute => $this->updatedByAttribute]);
595
    }
596
    
597
    /**
598
     *
599
     * @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...
600
     * @return boolean
601
     */
602 5
    public function setUpdater($updater)
603
    {
604 5
        if (!is_string($this->updatedByAttribute) || empty($this->updatedByAttribute)) {
605 1
            return false;
606
        }
607 4
        if ($updater instanceof $this->hostClass || $updater instanceof \yii\web\IdentityInterface) {
608 1
            return $this->{$this->updatedByAttribute} = $updater->getGUID();
609
        }
610 3
        if (is_string($updater) && preg_match(Number::GUID_REGEX, $updater)) {
611 1
            return $this->{$this->updatedByAttribute} = Number::guid_bin($updater);
612
        }
613 2
        if (strlen($updater) == 16) {
614 1
            return $this->{$this->updatedByAttribute} = $updater;
615
        }
616 1
        return false;
617
    }
618
619
    /**
620
     * This event is triggered before the model update.
621
     * This method is ONLY used for being triggered by event. DO NOT call,
622
     * override or modify it directly, unless you know the consequences.
623
     * @param ModelEvent $event
624
     */
625 57
    public function onContentChanged($event)
626
    {
627 57
        $sender = $event->sender;
628
        /* @var $sender static */
629 57
        return $sender->resetConfirmation();
630
    }
631
632
    /**
633
     * Return the current user's GUID if current model doesn't specify the owner
634
     * yet, or return the owner's GUID if current model has been specified.
635
     * This method is ONLY used for being triggered by event. DO NOT call,
636
     * override or modify it directly, unless you know the consequences.
637
     * @param ModelEvent $event
638
     * @return string the GUID of current user or the owner.
639
     */
640 140
    public function onGetCurrentUserGuid($event)
641
    {
642 140
        $sender = $event->sender;
643
        /* @var $sender static */
644 140
        if (isset($sender->attributes[$sender->createdByAttribute])) {
645 140
            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...
646
        }
647
        $identity = \Yii::$app->user->identity;
648
        /* @var $identity BaseUserModel */
649
        if ($identity) {
650
            return $identity->getGUID();
651
        }
652
    }
653
654
    /**
655
     * Initialize type of content. the first of element[index is 0] of
656
     * $contentTypes will be used.
657
     * @param ModelEvent $event
658
     */
659 22
    public function onInitContentType($event)
660
    {
661 22
        $sender = $event->sender;
662
        /* @var $sender static */
663 22
        if (!is_string($sender->contentTypeAttribute) || empty($sender->contentTypeAttribute)) {
664
            return;
665
        }
666 22
        $contentTypeAttribute = $sender->contentTypeAttribute;
667 22
        if (!isset($sender->$contentTypeAttribute) &&
668 22
            !empty($sender->contentTypes) &&
669 22
            is_array($sender->contentTypes)) {
670 22
            $sender->$contentTypeAttribute = $sender->contentTypes[0];
671
        }
672 22
    }
673
674
    /**
675
     * Initialize description property with $initDescription.
676
     * @param ModelEvent $event
677
     */
678 71
    public function onInitDescription($event)
679
    {
680 71
        $sender = $event->sender;
681
        /* @var $sender static */
682 71
        if (!is_string($sender->descriptionAttribute) || empty($sender->descriptionAttribute)) {
683
            return;
684
        }
685 71
        $descriptionAttribute = $sender->descriptionAttribute;
686 71
        if (empty($sender->$descriptionAttribute)) {
687 71
            $sender->$descriptionAttribute = $sender->initDescription;
688
        }
689 71
    }
690
691
    /**
692
     * Attaches an event handler to an event.
693
     *
694
     * The event handler must be a valid PHP callback. The following are
695
     * some examples:
696
     *
697
     * ```
698
     * function ($event) { ... }         // anonymous function
699
     * [$object, 'handleClick']          // $object->handleClick()
700
     * ['Page', 'handleClick']           // Page::handleClick()
701
     * 'handleClick'                     // global function handleClick()
702
     * ```
703
     *
704
     * The event handler must be defined with the following signature,
705
     *
706
     * ```
707
     * function ($event)
708
     * ```
709
     *
710
     * where `$event` is an [[Event]] object which includes parameters associated with the event.
711
     *
712
     * This method is provided by [[\yii\base\Component]].
713
     * @param string $name the event name
714
     * @param callable $handler the event handler
715
     * @param mixed $data the data to be passed to the event handler when the event is triggered.
716
     * When the event handler is invoked, this data can be accessed via [[Event::data]].
717
     * @param boolean $append whether to append new event handler to the end of the existing
718
     * handler list. If false, the new handler will be inserted at the beginning of the existing
719
     * handler list.
720
     * @see off()
721
     */
722
    public abstract function on($name, $handler, $data = null, $append = true);
723
724
    /**
725
     * Detaches an existing event handler from this component.
726
     * This method is the opposite of [[on()]].
727
     * This method is provided by [[\yii\base\Component]]
728
     * @param string $name event name
729
     * @param callable $handler the event handler to be removed.
730
     * If it is null, all handlers attached to the named event will be removed.
731
     * @return boolean if a handler is found and detached
732
     * @see on()
733
     */
734
    public abstract function off($name, $handler = null);
735
736
    /**
737
     * Attach events associated with blameable model.
738
     */
739 204
    public function initBlameableEvents()
740
    {
741 204
        $this->on(static::$eventConfirmationChanged, [$this, "onConfirmationChanged"]);
742 204
        $this->on(static::$eventNewRecordCreated, [$this, "onInitConfirmation"]);
743 204
        $contentTypeAttribute = $this->contentTypeAttribute;
744 204
        if (is_string($contentTypeAttribute) && !empty($contentTypeAttribute) && !isset($this->$contentTypeAttribute)) {
745 22
            $this->on(static::$eventNewRecordCreated, [$this, "onInitContentType"]);
746
        }
747 204
        $descriptionAttribute = $this->descriptionAttribute;
748 204
        if (is_string($descriptionAttribute) && !empty($descriptionAttribute) && !isset($this->$descriptionAttribute)) {
749 71
            $this->on(static::$eventNewRecordCreated, [$this, 'onInitDescription']);
750
        }
751 204
        $this->on(static::EVENT_BEFORE_UPDATE, [$this, "onContentChanged"]);
752 204
        $this->initSelfBlameableEvents();
753 204
    }
754
755
    /**
756
     * @inheritdoc
757
     */
758 85
    public function enabledFields()
759
    {
760 85
        $fields = parent::enabledFields();
761 85
        if (is_string($this->createdByAttribute) && !empty($this->createdByAttribute)) {
762 85
            $fields[] = $this->createdByAttribute;
763
        }
764 85
        if (is_string($this->updatedByAttribute) && !empty($this->updatedByAttribute) &&
765 85
            $this->createdByAttribute != $this->updatedByAttribute) {
766
            $fields[] = $this->updatedByAttribute;
767
        }
768 85
        if (is_string($this->contentAttribute)) {
769 85
            $fields[] = $this->contentAttribute;
770
        }
771 85
        if (is_array($this->contentAttribute)) {
772
            $fields = array_merge($fields, $this->contentAttribute);
773
        }
774 85
        if (is_string($this->descriptionAttribute)) {
775 1
            $fields[] = $this->descriptionAttribute;
776
        }
777 85
        if (is_string($this->confirmationAttribute)) {
778 1
            $fields[] = $this->confirmationAttribute;
779
        }
780 85
        if (is_string($this->parentAttribute)) {
781 1
            $fields[] = $this->parentAttribute;
782
        }
783 85
        return $fields;
784
    }
785
786
    /**
787
     * Find all follows by specified identity. If `$identity` is null, the logged-in
788
     * identity will be taken.
789
     * @param string|integer $pageSize If it is 'all`, then will find all follows,
790
     * the `$currentPage` parameter will be skipped. If it is integer, it will be
791
     * regarded as sum of models in one page.
792
     * @param integer $currentPage The current page number, begun with 0.
793
     * @param mixed $identity It's type depends on {$this->hostClass}.
794
     * @return static[] If no follows, null will be given, or return follow array.
795
     */
796 1
    public static function findAllByIdentityInBatch($pageSize = 'all', $currentPage = 0, $identity = null)
797
    {
798 1
        if ($pageSize === 'all') {
799 1
            return static::findByIdentity($identity)->all();
800
        }
801 1
        return static::findByIdentity($identity)->page($pageSize, $currentPage)->all();
802
    }
803
804
    /**
805
     * Find one follow by specified identity. If `$identity` is null, the logged-in
806
     * identity will be taken. If $identity doesn't has the follower, null will
807
     * be given.
808
     * @param integer $id user id.
809
     * @param boolean $throwException
810
     * @param mixed $identity It's type depends on {$this->hostClass}.
811
     * @return static
812
     * @throws InvalidParamException
813
     */
814 1
    public static function findOneById($id, $throwException = true, $identity = null)
815
    {
816 1
        $query = static::findByIdentity($identity);
817 1
        if (!empty($id)) {
818 1
            $query = $query->id($id);
819
        }
820 1
        $model = $query->one();
821 1
        if (!$model && $throwException) {
822 1
            throw new InvalidParamException('Model Not Found.');
823
        }
824 1
        return $model;
825
    }
826
827
    /**
828
     * Get total of follows of specified identity.
829
     * @param mixed $identity It's type depends on {$this->hostClass}.
830
     * @return integer total.
831
     */
832 3
    public static function countByIdentity($identity = null)
833
    {
834 3
        return (int)(static::findByIdentity($identity)->count());
835
    }
836
837
    /**
838
     * Get pagination, used for building contents page by page.
839
     * @param integer $limit
840
     * @param mixed $identity It's type depends on {$this->hostClass}.
841
     * @return Pagination
842
     */
843 2
    public static function getPagination($limit = 10, $identity = null)
844
    {
845 2
        $limit = (int) $limit;
846 2
        $count = static::countByIdentity($identity);
847 2
        if ($limit > $count) {
848 2
            $limit = $count;
849
        }
850 2
        return new Pagination(['totalCount' => $count, 'pageSize' => $limit]);
851
    }
852
}
853