IDTrait::getIdRules()   D
last analyzed

Complexity

Conditions 10
Paths 7

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 10.1371

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 30
ccs 16
cts 18
cp 0.8889
rs 4.8196
c 1
b 0
f 0
cc 10
eloc 20
nc 7
nop 0
crap 10.1371

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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;
17
use yii\base\ModelEvent;
18
19
/**
20
 * Entity features concerning ID.
21
 * @property-read array $idRules
22
 * @property mixed $ID
23
 * @version 1.0
24
 * @author vistart <[email protected]>
25
 */
26
trait IDTrait
27
{
28
    /**
29
     * @var string OPTIONAL. The attribute that will receive the IDentifier No.
30
     * You can set this property to false if you don't use this feature.
31
     */
32
    public $idAttribute = 'id';
33
    public static $idTypeString = 0;
34
    public static $idTypeInteger = 1;
35
    public static $idTypeAutoIncrement = 2;
36
37
    /**
38
     * @var integer type of id attribute.
39
     */
40
    public $idAttributeType = 0;
41
42
    /**
43
     * @var boolean Determines whether its ID has been pre-assigned. It will not
44
     * generate or assign ID if true.
45
     */
46
    public $idPreassigned = false;
47
48
    /**
49
     * @var string The prefix of ID. When ID type is Auto Increment, this feature
50
     * is skipped.
51
     */
52
    public $idAttributePrefix = '';
53
54
    /**
55
     * @var integer OPTIONAL. The length of id attribute value, and max length
56
     * of this attribute in rules. If you set $idAttribute to false or ID type
57
     * to Auto Increment, this property will be ignored.
58
     */
59
    public $idAttributeLength = 4;
60
61
    /**
62
     * @var boolean Determine whether the ID is safe for validation.
63
     */
64
    protected $idAttributeSafe = false;
65
66
    /**
67
     * Get ID.
68
     * @return string|integer
69
     */
70 30
    public function getID()
71
    {
72 30
        $idAttribute = $this->idAttribute;
73 30
        return (is_string($idAttribute) && !empty($idAttribute)) ? $this->$idAttribute : null;
74
    }
75
76
    /**
77
     * Set id.
78
     * @param string|integer $identity
79
     * @return string|integer
80
     */
81 377
    public function setID($identity)
82
    {
83 377
        $idAttribute = $this->idAttribute;
84 377
        return (is_string($idAttribute) && !empty($idAttribute)) ? $this->$idAttribute = $identity : null;
85
    }
86
87
    /**
88
     * Attach `onInitGuidAttribute` event.
89
     * @param string $eventName
90
     */
91 392
    protected function attachInitIDEvent($eventName)
92
    {
93 392
        $this->on($eventName, [$this, 'onInitIDAttribute']);
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...
94 392
    }
95
96
    /**
97
     * Initialize the ID attribute with new generated ID.
98
     * If the model's id is pre-assigned, then it will return directly.
99
     * If the model's id is auto-increment, the id attribute will be marked safe.
100
     * This method is ONLY used for being triggered by event. DO NOT call,
101
     * override or modify it directly, unless you know the consequences.
102
     * @param ModelEvent $event
103
     */
104 392
    public function onInitIDAttribute($event)
105
    {
106 392
        $sender = $event->sender;
107
        /* @var $sender static */
108 392
        if ($sender->idPreassigned) {
109 219
            return;
110
        }
111 392
        if ($sender->idAttributeType === static::$idTypeAutoIncrement) {
112 77
            $sender->idAttributeSafe = true;
113 77
            return;
114
        }
115 377
        $idAttribute = $sender->idAttribute;
116 377
        if (is_string($idAttribute) && !empty($idAttribute) &&
117 377
            is_int($sender->idAttributeLength) &&
118 377
            $sender->idAttributeLength > 0) {
119 377
            $sender->setID($sender->generateId());
0 ignored issues
show
Bug introduced by
It seems like $sender->generateId() targeting rhosocial\base\models\traits\IDTrait::generateId() can also be of type false or null; however, rhosocial\base\models\traits\IDTrait::setID() does only seem to accept string|integer, maybe add an additional type check?

This check looks at variables that 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...
120
        }
121 377
    }
122
123
    /**
124
     * Generate the ID. You can override this method to implement your own
125
     * generation algorithm.
126
     * @return string the generated ID.
127
     */
128 377
    public function generateId()
129
    {
130 377
        if ($this->idAttributeType == static::$idTypeInteger) {
131
            do {
132 307
                $result = Number::randomNumber($this->idAttributePrefix, $this->idAttributeLength);
133 307
            } while ($this->checkIdExists((int) $result));
134 307
            return $result;
135
        }
136 224
        if ($this->idAttributeType == static::$idTypeString) {
137 224
            return $this->idAttributePrefix .
138 224
                Yii::$app->security->generateRandomString($this->idAttributeLength - strlen($this->idAttributePrefix));
139
        }
140 1
        if ($this->idAttributeType == static::$idTypeAutoIncrement) {
141 1
            return null;
142
        }
143
        return false;
144
    }
145
    
146
    /**
147
     * Check if $identity existed.
148
     * @param mixed $identity
149
     * @return boolean
150
     */
151 308
    public function checkIdExists($identity)
152
    {
153 308
        if ($identity == null) {
154 4
            return false;
155
        }
156 308
        return static::find()->where([$this->idAttribute => $identity])->exists();
157
    }
158
159
    /**
160
     * Get the rules associated with id attribute.
161
     * @return array
162
     */
163 361
    public function getIdRules()
164
    {
165 361
        if ($this->idAttribute == false) {
166
            return [];
167
        }
168 361
        if ($this->idAttributeSafe || $this->idAttributeType === static::$idTypeAutoIncrement) {
169
            return [
170 75
                [[$this->idAttribute], 'safe'],
171
            ];
172
        }
173 345
        if (is_string($this->idAttribute) && !empty($this->idAttribute) &&
174 345
            is_int($this->idAttributeLength) &&
175 345
            $this->idAttributeLength > 0) {
176
            $rules = [
177 345
                [[$this->idAttribute], 'required'],
178 345
                [[$this->idAttribute], 'unique'],
179
            ];
180 345
            if ($this->idAttributeType === static::$idTypeInteger) {
181 293
                $rules[] = [
182 293
                    [$this->idAttribute], 'number', 'integerOnly' => true
183
                ];
184
            }
185 345
            if ($this->idAttributeType === static::$idTypeString) {
186 103
                $rules[] = [[$this->idAttribute], 'string',
187 103
                    'max' => $this->idAttributeLength,];
188
            }
189 345
            return $rules;
190
        }
191
        return [];
192
    }
193
194
    /**
195
     * Composite IDs from models.
196
     * @param $models
197
     * @return array|int|string
198
     */
199 1
    public static function compositeIDs($models)
200
    {
201 1
        if (!is_array($models) && $models instanceof static) {
202 1
            return $models->getID();
203
        }
204 1
        $ids = [];
205 1
        foreach ($models as $model) {
206 1
            if ($model instanceof static) {
207 1
                $ids[] = $model->getID();
208
            }
209
        }
210 1
        return $ids;
211
    }
212
}
213
214