Test Failed
Push — master ( 5196a6...aaaa1a )
by vistart
08:44
created

MultipleBlameableTrait::unsetInvalidBlames()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 16
ccs 11
cts 12
cp 0.9167
rs 9.4285
cc 3
eloc 12
nc 3
nop 1
crap 3.0052
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\events\MultipleBlameableEvent;
17
use rhosocial\base\models\models\BaseUserModel;
18
use yii\base\ModelEvent;
19
use yii\base\InvalidCallException;
20
use yii\base\InvalidConfigException;
21
use yii\base\InvalidParamException;
22
23
/**
24
 * 一个模型的某个属性可能对应多个责任者,该 trait 用于处理此种情况。此种情况违反
25
 * 了关系型数据库第一范式,因此此 trait 只适用于责任者属性修改不频繁的场景,在开
26
 * 发时必须严格测试数据一致性,并同时考量性能。
27
 * Basic Principles:
28
 * <ol>
29
 * <li>when adding blame, it will check whether each of blames including to be
30
 * added is valid.
31
 * </li>
32
 * <li>when removing blame, as well as counting, getting or setting list of them,
33
 * it will also check whether each of blames is valid.
34
 * </li>
35
 * <li>By default, once blame was deleted, the guid of it is not removed from
36
 * list of blames immediately. It will check blame if valid when adding, removing,
37
 * counting, getting and setting it. You can define a blame model and attach it
38
 * events triggered when inserting, updating and deleting a blame, then disable
39
 * checking the validity of blames.
40
 * </li>
41
 * </ol>
42
 * Notice:
43
 * <ol>
44
 * <li>You must specify two properties: $multiBlamesClass and $multiBlamesAttribute.
45
 * <ul>
46
 * <li>$multiBlamesClass specify the class name of blame.</li>
47
 * <li>$multiBlamesAttribute specify the field name of blames.</li>
48
 * </ul>
49
 * </li>
50
 * <li>You should rename the following methods to be needed optionally.</li>
51
 * </ol>
52
 * @property-read array $multiBlamesAttributeRules
53
 * @property string[] $blameGuids
54
 * @property-read array $allBlames
55
 * @property-read array $nonBlameds
56
 * @property-read integer $blamesCount
57
 * @version 1.0
58
 * @author vistart <[email protected]>
59
 */
60
trait MultipleBlameableTrait
61
{
62
63
    /**
64
     * @var string class name of multiple blameable class.
65
     */
66
    public $multiBlamesClass = '';
67
68
    /**
69
     * @var string name of multiple blameable attribute.
70
     */
71
    public $multiBlamesAttribute = 'blames';
72
73
    /**
74
     * @var integer the limit of blames. it should be greater than or equal 1, and
75
     * less than or equal 10.
76
     */
77
    public $blamesLimit = 10;
78
79
    /**
80
     * @var boolean determines whether blames list has been changed.
81
     */
82
    public $blamesChanged = false;
83
84
    /**
85
     * @var string event name.
86
     */
87
    public static $eventMultipleBlamesChanged = 'multipleBlamesChanged';
88
89
    /**
90
     * Get the rules associated with multiple blameable attribute.
91
     * @return array rules.
92
     */
93 46
    public function getMultipleBlameableAttributeRules()
94
    {
95 46
        return is_string($this->multiBlamesAttribute) ? [
96 46
            [[$this->multiBlamesAttribute], 'string', 'max' => $this->blamesLimit * 16],
97 46
            [[$this->multiBlamesAttribute], 'default', 'value' => ''],
98 46
            ] : [];
99
    }
100
101
    /**
102
     * Add specified blame.
103
     * @param {$this->multiBlamesClass}|string $blame
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass}|string 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...
104
     * @return false|array
105
     * @throws InvalidParamException if blame existed.
106
     * @throws InvalidCallException if blame limit reached.
107
     */
108 8
    public function addBlame($blame)
109
    {
110 8
        if (!is_string($this->multiBlamesAttribute)) {
111
            return false;
112
        }
113 8
        $blameGuid = '';
114 8
        if (is_string($blame)) {
115 3
            $blameGuid = $blame;
116
        }
117 8
        if ($blame instanceof $this->multiBlamesClass) {
118 5
            $blameGuid = $blame->getGUID();
119
        }
120 8
        $blameGuids = $this->getBlameGuids(true);
121 8
        if (array_search($blameGuid, $blameGuids)) {
122
            throw new InvalidParamException('the blame has existed.');
123
        }
124 8
        if ($this->getBlamesCount() >= $this->blamesLimit) {
125
            throw new InvalidCallException("the limit($this->blamesLimit) of blames has been reached.");
126
        }
127 8
        $blameGuids[] = $blameGuid;
128 8
        $this->setBlameGuids($blameGuids);
129 8
        return $this->getBlameGuids();
130
    }
131
132
    /**
133
     * Create blame.
134
     * @param BaseUserModel $user who will own this blame.
135
     * @param array $config blame class configuration array.
136
     * @return {$this->multiBlamesClass}
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass} 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...
137
     */
138 10
    public static function createBlame($user, $config = [])
139
    {
140 10
        if (!($user instanceof BaseUserModel)) {
141 2
            $message = 'the type of user instance must be the extended class of BaseUserModel.';
142 2
            throw new InvalidParamException($message);
143
        }
144 9
        $mbClass = static::buildNoInitModel();
145 9
        $mbi = $mbClass->multiBlamesClass;
146 9
        return $user->create($mbi::className(), $config);
147
    }
148
149
    /**
150
     * Add specified blame, or create it before adding if doesn't exist.
151
     * But you should save the blame instance before adding it, or the operation
152
     * will fail.
153
     * @param {$this->multiBlamesClass}|string|array $blame
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass}|string|array 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...
154
     * It will be regarded as blame's guid if it is a string. And assign the
155
     * reference parameter $blame the instance if it existed, or create one if not
156
     * found.
157
     * If it is {$this->multiBlamesClass} instance and existed, then will add it, or
158
     * false will be given if it is not found in database. So if you want to add
159
     * blame instance, you should save it before adding.
160
     * If it is a array, it will be regarded as configuration array of blame.
161
     * Notice! This parameter passed by reference, so it must be a variable!
162
     * @param BaseUserModel $user whose blame.
163
     * If null, it will take this blameable model's user.
164
     * @return false|array false if blame created failed or not enable this feature.
165
     * blames guid array if created and added successfully.
166
     * @throws InvalidConfigException
167
     * @throws InvalidParamException
168
     * @see addBlame()
169
     */
170 4
    public function addOrCreateBlame(&$blame = null, $user = null)
171
    {
172 4
        if (!is_string($this->multiBlamesClass)) {
173
            throw new InvalidConfigException
174
            ('$multiBlamesClass must be specified if you want to use multiple blameable features.');
175
        }
176 4
        if (is_array($blame) || $blame === null) {
177 3
            if ($user == null) {
178 3
                $user = $this->host;
0 ignored issues
show
Bug introduced by
The property host 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...
179
            }
180 3
            $blame = static::getOrCreateBlame($blame, $user);
181 3
            if (!$blame->save()) {
182
                return false;
183
            }
184 3
            return $this->addBlame($blame->getGUID());
185
        }
186 1
        $blameGuid = '';
187 1
        if (is_string($blame)) {
188
            $blameGuid = $blame;
189
        }
190 1
        if ($blame instanceof $this->multiBlamesClass) {
191 1
            $blameGuid = $blame->getGUID();
192
        }
193 1
        if (($mbi = static::getBlame($blameGuid)) !== null) {
194 1
            return $this->addBlame($mbi);
195
        }
196
        return false;
197
    }
198
199
    /**
200
     * Remove specified blame.
201
     * @param {$this->multiBlamesClass}|string $blame
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass}|string 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...
202
     * @return false|array all guids in json format.
203
     */
204 1
    public function removeBlame($blame)
205
    {
206 1
        if (!is_string($this->multiBlamesAttribute)) {
207
            return false;
208
        }
209 1
        $blameGuid = '';
210 1
        if (is_string($blame)) {
211 1
            $blameGuid = $blame;
212
        }
213 1
        if ($blame instanceof $this->multiBlamesClass) {
214 1
            $blameGuid = $blame->getGUID();
215
        }
216 1
        $blameGuids = $this->getBlameGuids(true);
217 1
        if (($key = array_search($blameGuid, $blameGuids)) !== false) {
218 1
            unset($blameGuids[$key]);
219 1
            $this->setBlameGuids($blameGuids);
220
        }
221 1
        return $this->getBlameGuids();
222
    }
223
224
    /**
225
     * Remove all blames.
226
     */
227 49
    public function removeAllBlames()
228
    {
229 49
        $this->setBlameGuids();
230 49
    }
231
232
    /**
233
     * Count the blames.
234
     * @return integer
235
     */
236 8
    public function getBlamesCount()
237
    {
238 8
        return count($this->getBlameGuids(true));
239
    }
240
241
    /**
242
     * Get the guid array of blames. it may check all guids if valid before return.
243
     * @param boolean $checkValid determines whether checking the blame is valid.
244
     * @return array all guids in json format.
245
     */
246 8
    public function getBlameGuids($checkValid = false)
247
    {
248 8
        $multiBlamesAttribute = $this->multiBlamesAttribute;
249 8
        if ($multiBlamesAttribute === false) {
250
            return [];
251
        }
252 8
        $guids = Number::divide_guid_bin($this->$multiBlamesAttribute);
253 8
        if ($checkValid) {
254 8
            $guids = $this->unsetInvalidBlames($guids);
255
        }
256 8
        return $guids;
257
    }
258
259
    /**
260
     * Event triggered when blames list changed.
261
     * @param MultipleBlameableEvent $event
262
     */
263 49
    public function onBlamesChanged($event)
264
    {
265 49
        $sender = $event->sender;
266 49
        $sender->blamesChanged = $event->blamesChanged;
267 49
    }
268
269
    /**
270
     * Remove invalid blame guid from provided guid array.
271
     * @param array $guids guid array of blames.
272
     * @return array guid array of blames unset invalid.
273
     */
274 49
    protected function unsetInvalidBlames($guids)
275
    {
276 49
        $unchecked = $guids;
277 49
        $multiBlamesClass = $this->multiBlamesClass;
278 49
        $mbi = $multiBlamesClass::buildNoInitModel();
279 49
        foreach ($guids as $key => $guid) {
280 8
            $blame = $multiBlamesClass::find()->where([$mbi->guidAttribute => $guid])->exists();
281 8
            if (!$blame) {
282
                unset($guids[$key]);
283
            }
284
        }
285 49
        $diff = array_diff($unchecked, $guids);
286 49
        $eventName = static::$eventMultipleBlamesChanged;
287 49
        $this->trigger($eventName, new MultipleBlameableEvent(['blamesChanged' => !empty($diff)]));
0 ignored issues
show
Bug introduced by
It seems like trigger() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
288 49
        return $guids;
289
    }
290
291
    /**
292
     * Set the guid array of blames, it may check all guids if valid.
293
     * @param array $guids guid array of blames.
294
     * @param boolean $checkValid determines whether checking the blame is valid.
295
     * @return false|array all guids.
296
     */
297 49
    public function setBlameGuids($guids = [], $checkValid = true)
298
    {
299 49
        if (!is_array($guids) || $this->multiBlamesAttribute === false) {
300
            return null;
301
        }
302 49
        if ($checkValid) {
303 49
            $guids = $this->unsetInvalidBlames($guids);
304
        }
305 49
        $multiBlamesAttribute = $this->multiBlamesAttribute;
306 49
        $this->$multiBlamesAttribute = Number::composite_guid($guids);
307 49
        return $guids;
308
    }
309
310
    /**
311
     * Get blame.
312
     * @param string $blameGuid
313
     * @return {$this->multiBlamesClass}
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass} 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...
314
     */
315 6
    public static function getBlame($blameGuid)
316
    {
317 6
        $self = static::buildNoInitModel();
318 6
        if (empty($blameGuid) || empty($self->multiBlamesClass) ||
319 5
            !is_string($self->multiBlamesClass) || $self->multiBlamesAttribute === false) {
320 1
            return null;
321
        }
322 5
        $mbClass = $self->multiBlamesClass;
323 5
        return $mbClass::findOne($blameGuid);
324
    }
325
    
326
    /**
327
     * Get all blames that owned this relation.
328
     * @return array
329
     */
330 2
    public function getOwnBlames()
331
    {
332 2
        $guids = $this->getBlameGuids(true);
333 2
        $class = $this->multiBlamesClass;
334 2
        return $class::findAll($guids);
335
    }
336
    
337
    /**
338
     * Set blames which would own this relation.
339
     * @param array $blames
340
     */
341
    public function setOwnBlames($blames)
342
    {
343
        $guids = static::compositeGUIDs($blames);
344
        return $this->setBlameGuids($guids, true);
345
    }
346
    
347
    /**
348
     * Check blame owned this.
349
     * @param {$this->multiBlamesClass} $blame
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass} 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...
350
     * @return boolean
351
     */
352 2
    public function isBlameOwned($blame)
353
    {
354 2
        if (!($blame instanceof $this->multiBlamesClass) ||
355 1
            $blame->getIsNewRecord() || !static::getBlame($blame->getGUID())) {
356 1
            return false;
357
        }
358 1
        return array_search($blame->getGUID(), $this->getBlameGuids(true));
359
    }
360
361
    /**
362
     * Get or create blame.
363
     * @param string|array|null $blameGuid
364
     * @param BaseUserModel $user
365
     * @return {$this->multiBlamesClass}|null
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass}|null 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...
366
     */
367 4
    public static function getOrCreateBlame($blameGuid, $user = null)
368
    {
369 4
        if (is_string($blameGuid)) {
370 1
            return static::getBlame($blameGuid);
371
        }
372 4
        if (is_array($blameGuid) || $blameGuid === null) {
373 4
            return static::createBlame($user, $blameGuid);
0 ignored issues
show
Bug introduced by
It seems like $user defined by parameter $user on line 367 can be null; however, rhosocial\base\models\tr...bleTrait::createBlame() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Bug introduced by
It seems like $blameGuid defined by parameter $blameGuid on line 367 can also be of type null; however, rhosocial\base\models\tr...bleTrait::createBlame() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
374
        }
375 1
        return null;
376
    }
377
378
    /**
379
     * Get all ones to be blamed by `$blame`.
380
     * @param {$this->multiBlamesClass} $blame
0 ignored issues
show
Documentation introduced by
The doc-type {$this->multiBlamesClass} 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...
381
     * @return array
382
     */
383 2
    public static function getBlameds($blame)
384
    {
385 2
        if (is_string($blame)) {
386 1
            $blame = static::getBlame($blame);
387
        }
388 2
        if (empty($blame)) {
389 1
            return [];
390
        }
391 1
        $noInit = static::buildNoInitModel();
392
        /* @var $noInit static */
393 1
        return static::find()->createdBy($blame->host)->
394 1
                andWhere(['like', $noInit->multiBlamesAttribute, $blame->getGUID()])->all();
395
    }
396
397
    /**
398
     * Get all the blames of record.
399
     * @param BaseUserModel $user
400
     * @return array all blames.
401
     */
402 2
    public static function getAllBlames($user)
403
    {
404 2
        $noInit = static::buildNoInitModel();
405 2
        if (empty($noInit->multiBlamesClass) ||
406 2
            !is_string($noInit->multiBlamesClass) ||
407 2
            $noInit->multiBlamesAttribute === false) {
408
            return null;
409
        }
410 2
        $multiBlamesClass = $noInit->multiBlamesClass;
411 2
        $createdByAttribute = $noInit->createdByAttribute;
412 2
        return $multiBlamesClass::findAll([$createdByAttribute => $user->getGUID()]);
413
    }
414
415
    /**
416
     * Get all records which without any blames.
417
     * @param BaseUserModel $user
418
     * @return array all non-blameds.
419
     */
420 1
    public static function getNonBlameds($user = null)
421
    {
422 1
        $noInit = static::buildNoInitModel();
423
        /* @var $noInit static */
424 1
        $createdByAttribute = $noInit->createdByAttribute;
0 ignored issues
show
Bug introduced by
The property createdByAttribute 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...
425 1
        if (!$user) {
426
            $user = \Yii::$app->user->identity;
427
        }
428
        $cond = [
429 1
            $createdByAttribute => $user->getGUID(),
430 1
            $noInit->multiBlamesAttribute => ''
431
        ];
432 1
        return static::find()->where($cond)->all();
433
    }
434
435
    /**
436
     * Initialize blames limit.
437
     * @param ModelEvent $event
438
     */
439 49
    public function onInitBlamesLimit($event)
440
    {
441 49
        $sender = $event->sender;
442 49
        if (!is_int($sender->blamesLimit) || $sender->blamesLimit < 1 || $sender->blamesLimit > 64) {
443
            $sender->blamesLimit = 10;
444
        }
445 49
    }
446
    
447
    /**
448
     * Get blames which do not own any model.
449
     * @param BaseUserModel $user
450
     */
451 1
    public static function getEmptyBlames($user)
452
    {
453 1
        $blames = static::getAllBlames($user);
454 1
        $emptyGroups = [];
455 1
        $noInit = static::buildNoInitModel();
456 1
        foreach ($blames as $blame) {
457 1
            if (static::find()->createdBy($user)->
458 1
                    andWhere(['like', $noInit->multiBlamesAttribute, $blame->getGUID()])->exists()) {
459 1
                continue;
460
            }
461 1
            $emptyGroups[] = $blame;
462
        }
463 1
        return $emptyGroups;
464
    }
465
}
466