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

GUIDTrait::onInitGUIDAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
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 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 yii\base\ModelEvent;
17
18
/**
19
 * Entity features concerning GUID.
20
 * @property string $GUID GUID value in 128-bit(16 bytes) binary format.
21
 * @property-read string $readableGUID Readable GUID value seperated with four hyphens.
22
 * @property-read array $guidRules
23
 * @version 1.0
24
 * @author vistart <[email protected]>
25
 */
26
trait GUIDTrait
27
{
28
    
29
    /**
30
     * @var string REQUIRED. The attribute that will receive the GUID value.
31
     */
32
    public $guidAttribute = 'guid';
33
    
34
    /**
35
     * DO NOT MODIFY OR OVERRIDE THIS METHOD UNLESS YOU KNOW THE CONSEQUENCES.
36
     * @return string
37
     */
38 3
    public function getReadableGuidAttribute()
39
    {
40 3
        return 'readableGuid';
41
    }
42
    
43
    /**
44
     * Attach `onInitGUIDAttribute` event.
45
     * @param string $eventName
46
     */
47 379
    protected function attachInitGUIDEvent($eventName)
48
    {
49 379
        $this->on($eventName, [$this, 'onInitGUIDAttribute']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

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

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

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

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

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

Loading history...
50 379
    }
51
    
52
    /**
53
     * Initialize the GUID attribute with new generated GUID.
54
     * This method is ONLY used for being triggered by event. DO NOT call,
55
     * ovveride or modify it directly, unless you know the conquences.
56
     * @param ModelEvent $event
57
     */
58 379
    public function onInitGUIDAttribute($event)
59
    {
60 379
        $sender = $event->sender;
61
        /* @var $sender static */
62 379
        $sender->setGUID(static::generateGuid());
63 379
    }
64
65
    /**
66
     * Generate GUID in binary.
67
     * @return string GUID.
68
     */
69 379
    public static function generateGuid()
70
    {
71 379
        return Number::guid_bin();
72
    }
73
74
    /**
75
     * Check if the $guid existed in current database table.
76
     * @param string $guid the GUID to be checked.
77
     * @return boolean Whether the $guid exists or not.
78
     */
79 3
    public static function checkGuidExists($guid)
80
    {
81 3
        return static::findOne($guid) !== null;
82
    }
83
    
84
    /**
85
     * Get the rules associated with GUID attribute.
86
     * @return array GUID rules.
87
     */
88 337
    public function getGUIDRules()
89
    {
90 337
        $rules = [];
91 337
        if (is_string($this->guidAttribute) && !empty($this->guidAttribute)) {
92
            $rules = [
93 316
                [[$this->guidAttribute], 'required',],
94 316
                [[$this->guidAttribute], 'unique',],
95 316
                [[$this->guidAttribute], 'string', 'max' => 16],
96
            ];
97
        }
98 337
        return $rules;
99
    }
100
    
101
    /**
102
     * Get GUID, in spite of guid attribute name.
103
     * @return string
104
     */
105 242
    public function getGUID()
106
    {
107 242
        $guidAttribute = $this->guidAttribute;
108 242
        return (is_string($guidAttribute) && !empty($guidAttribute)) ? $this->$guidAttribute : null;
109
    }
110
    
111
    /**
112
     * Get Readable GUID.
113
     * @return string
114
     */
115 15
    public function getReadableGUID()
116
    {
117 15
        $guid = $this->getGUID();
118 15
        if (preg_match(Number::GUID_REGEX, $guid)) {
119 3
            return $guid;
120
        }
121 12
        return Number::guid(false, false, $guid);
122
    }
123
124
    /**
125
     * Set guid, in spite of guid attribute name.
126
     * @param string $guid
127
     * @return string
128
     */
129 364
    public function setGUID($guid)
130
    {
131 364
        $guidAttribute = $this->guidAttribute;
132 364
        if (preg_match(Number::GUID_REGEX, $guid)) {
133 3
            $guid = hex2bin(str_replace(['{', '}', '-'], '', $guid));
134
        }
135 364
        return (is_string($guidAttribute) && !empty($guidAttribute)) ? $this->$guidAttribute = $guid : null;
136
    }
137
    
138
    /**
139
     * Composite GUIDs from models.
140
     * @param array|string $models
141
     * @return array
142
     */
143 51
    public static function compositeGUIDs($models)
144
    {
145 51
        if (empty($models)) {
146 14
            return null;
147
        }
148 51
        if (!is_array($models) && $models instanceof static) {
149 49
            return $models->getGUID();
150
        }
151 4
        if (is_string($models) && strlen($models) == 16) {
152 2
            return $models;
153
        }
154 2
        $guids = [];
155 2
        foreach ($models as $model) {
0 ignored issues
show
Bug introduced by
The expression $models of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
156 2
            if ($model instanceof static) {
157 2
                $guids[] = $model->getGUID();
158
            } elseif (is_string($model)) {
159
                if (strlen($model) == 16) {
160
                    $guids[] = $model;
161
                } elseif (preg_match(Number::GUID_REGEX, $model)) {
162
                    $guids[] = Number::guid_bin($model);
163
                }
164
            }
165
        }
166 2
        return $guids;
167
    }
168
}