1 | <?php |
||
24 | trait GUIDTrait |
||
25 | { |
||
26 | |||
27 | /** |
||
28 | * @var string REQUIRED. The attribute that will receive the GUID value. |
||
29 | */ |
||
30 | public $guidAttribute = 'guid'; |
||
31 | |||
32 | /** |
||
33 | * Attach `onInitGuidAttribute` event. |
||
34 | * @param string $eventName |
||
35 | */ |
||
36 | 48 | protected function attachInitGuidEvent($eventName) |
|
40 | |||
41 | /** |
||
42 | * Initialize the GUID attribute with new generated GUID. |
||
43 | * This method is ONLY used for being triggered by event. DO NOT call, |
||
44 | * override or modify it directly, unless you know the consequences. |
||
45 | * @param \yii\base\Event $event |
||
46 | * @since 1.1 |
||
47 | */ |
||
48 | 48 | public function onInitGuidAttribute($event) |
|
49 | { |
||
50 | 48 | $sender = $event->sender; |
|
51 | 48 | $guidAttribute = $sender->guidAttribute; |
|
52 | 48 | if (is_string($guidAttribute)) { |
|
53 | 47 | $sender->$guidAttribute = static::generateGuid(); |
|
54 | 47 | } |
|
55 | 48 | } |
|
56 | |||
57 | /** |
||
58 | * Generate GUID. It will check if the generated GUID existed in database |
||
59 | * table, if existed, it will regenerate one. |
||
60 | * @return string the generated GUID. |
||
61 | */ |
||
62 | 47 | public static function generateGuid() |
|
66 | |||
67 | /** |
||
68 | * Check if the $uuid existed in current database table. |
||
69 | * @param string $guid the GUID to be checked. |
||
70 | * @return boolean Whether the $guid exists or not. |
||
71 | */ |
||
72 | public static function checkGuidExists($guid) |
||
76 | |||
77 | /** |
||
78 | * Get the rules associated with guid attribute. |
||
79 | * @return array rules. |
||
80 | */ |
||
81 | 15 | public function getGuidRules() |
|
82 | { |
||
83 | 15 | $rules = []; |
|
84 | 15 | if (is_string($this->guidAttribute)) { |
|
85 | $rules = [ |
||
86 | 10 | [[$this->guidAttribute], 'required',], |
|
87 | 10 | [[$this->guidAttribute], 'unique',], |
|
88 | 10 | [[$this->guidAttribute], 'string', 'max' => 36], |
|
89 | 10 | ]; |
|
90 | 10 | } |
|
91 | 15 | return $rules; |
|
92 | } |
||
93 | |||
94 | /** |
||
95 | * Get guid, in spite of guid attribute name. |
||
96 | * @return string |
||
97 | */ |
||
98 | public function getGuid() |
||
103 | |||
104 | /** |
||
105 | * Set guid, in spite of guid attribute name. |
||
106 | * @param string $guid |
||
107 | * @return string |
||
108 | */ |
||
109 | public function setGuid($guid) |
||
114 | } |
||
115 |
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
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. 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.