Completed
Push — master ( 69007e...64430c )
by vistart
05:40
created

MultipleBlameableTrait::onBlamesChanged()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
240 2
        if ($checkValid) {
241 2
            $guids = $this->unsetInvalidBlames($guids);
242 2
        }
243 2
        return $guids;
244
    }
245
246
    /**
247
     * Event triggered when blames list changed.
248
     * @param \vistart\Models\events\MultipleBlameableEvent $event
249
     */
250 8
    public function onBlamesChanged($event)
251
    {
252 8
        $sender = $event->sender;
253 8
        $sender->blamesChanged = $event->blamesChanged;
254 8
    }
255
256
    /**
257
     * Remove invalid blame guid from provided guid array.
258
     * @param array $guids guid array of blames.
259
     * @return array guid array of blames unset invalid.
260
     */
261 8
    protected function unsetInvalidBlames($guids)
262
    {
263 8
        $checkedGuids = Number::unsetInvalidUuids($guids);
264 8
        $multiBlamesClass = $this->multiBlamesClass;
265 8
        foreach ($checkedGuids as $key => $guid) {
266 2
            $blame = $multiBlamesClass::findOne($guid);
267 2
            if (!$blame) {
268 1
                unset($checkedGuids[$key]);
269 1
            }
270 8
        }
271 8
        $diff = array_diff($guids, $checkedGuids);
272 8
        $eventName = static::$eventMultipleBlamesChanged;
273 8
        $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...
274 8
        return $checkedGuids;
275
    }
276
277
    /**
278
     * Set the guid array of blames, it may check all guids if valid.
279
     * @param array $guids guid array of blames.
280
     * @param boolean $checkValid determines whether checking the blame is valid.
281
     * @return false|array all guids.
282
     */
283 8
    public function setBlameGuids($guids = [], $checkValid = true)
284
    {
285 8
        if (!is_array($guids) || $this->multiBlamesAttribute === false) {
286
            return null;
287
        }
288 8
        if ($checkValid) {
289 8
            $guids = $this->unsetInvalidBlames($guids);
290 8
        }
291 8
        $multiBlamesAttribute = $this->multiBlamesAttribute;
292 8
        $this->$multiBlamesAttribute = json_encode(array_values($guids));
293 8
        return $guids;
294
    }
295
296
    /**
297
     * Get blame.
298
     * @param string $blameGuid
299
     * @return [multiBlamesClass]
0 ignored issues
show
Documentation introduced by
The doc-type [multiBlamesClass] could not be parsed: Unknown type name "" 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...
300
     */
301 2
    public static function getBlame($blameGuid)
302
    {
303 2
        $self = static::buildNoInitModel();
304 2
        if (empty($self->multiBlamesClass) || !is_string($self->multiBlamesClass) || $self->multiBlamesAttribute === false) {
305
            return null;
306
        }
307 2
        $mbClass = $self->multiBlamesClass;
308 2
        return $mbClass::findOne($blameGuid);
309
    }
310
311
    /**
312
     * Get or create blame.
313
     * @param string|array $blameGuid
314
     * @param \vistart\Models\models\BaseUserClass $user
315
     * @return [multiBlamesClass]|null
0 ignored issues
show
Documentation introduced by
The doc-type [multiBlamesClass]|null could not be parsed: Unknown type name "" 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...
316
     */
317 1
    public static function getOrCreateBlame($blameGuid, $user = null)
318
    {
319 1
        if (is_string($blameGuid)) {
320
            $blameGuid = static::getBlame($blameGuid);
321
            if ($blameGuid !== null) {
322
                return $blameGuid;
323
            }
324
        }
325 1
        if (is_array($blameGuid)) {
326 1
            return static::createBlame($user, $blameGuid);
0 ignored issues
show
Bug introduced by
It seems like $user defined by parameter $user on line 317 can also be of type null; however, vistart\Models\traits\Mu...bleTrait::createBlame() does only seem to accept object<vistart\Models\models\BaseUserModel>, 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...
327
        }
328
        return null;
329
    }
330
331
    /**
332
     * Get all ones to be blamed by `$blame`.
333
     * @param [multiBlamesClass] $blame
0 ignored issues
show
Documentation introduced by
The doc-type [multiBlamesClass] could not be parsed: Unknown type name "" 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...
334
     * @return array
335
     */
336 1
    public function getBlameds($blame)
337
    {
338 1
        $blameds = static::getBlame($blame->guid);
339 1
        if (empty($blameds)) {
340 1
            return null;
341
        }
342 1
        $createdByAttribute = $this->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...
343 1
        return static::find()->where([$createdByAttribute => $this->$createdByAttribute])
344 1
                ->andWhere(['like', $this->multiBlamesAttribute, $blame->guid])->all();
345
    }
346
347
    /**
348
     * Get all the blames of record.
349
     * @return array all blames.
350
     */
351 1
    public function getAllBlames()
352
    {
353 1
        if (empty($this->multiBlamesClass) ||
354 1
            !is_string($this->multiBlamesClass) ||
355 1
            $this->multiBlamesAttribute === false) {
356
            return null;
357
        }
358 1
        $multiBlamesClass = $this->multiBlamesClass;
359 1
        $createdByAttribute = $this->createdByAttribute;
360 1
        return $multiBlamesClass::findAll([$createdByAttribute => $this->$createdByAttribute]);
361
    }
362
363
    /**
364
     * Get all records which without any blames.
365
     * @return array all non-blameds.
366
     */
367 1
    public function getNonBlameds()
368
    {
369 1
        $createdByAttribute = $this->createdByAttribute;
370
        $cond = [
371 1
            $createdByAttribute => $this->$createdByAttribute,
372 1
            $this->multiBlamesAttribute => static::getEmptyBlamesJson()
373 1
        ];
374 1
        return static::find()->where($cond)->all();
375
    }
376
377
    /**
378
     * Initialize blames limit.
379
     * @param \yii\base\Event $event
380
     */
381 8
    public function onInitBlamesLimit($event)
382
    {
383 8
        $sender = $event->sender;
384 8
        if (!is_int($sender->blamesLimit) || $sender->blamesLimit < 1 || $sender->blamesLimit > 10) {
385
            $sender->blamesLimit = 10;
386
        }
387 8
    }
388
389
    /**
390
     * Get the json of empty blames array.
391
     * @return string
392
     */
393 1
    public static function getEmptyBlamesJson()
394
    {
395 1
        return json_encode([]);
396
    }
397
}
398