1 | <?php |
||
25 | trait UserUsernameTrait |
||
26 | { |
||
27 | public $usernameClass = false; |
||
28 | |||
29 | /** |
||
30 | * Check whether this user enables the username feature or not. |
||
31 | * @return boolean |
||
32 | */ |
||
33 | 4 | public function hasEnabledUsername() |
|
40 | |||
41 | /** |
||
42 | * Get username. |
||
43 | * This method may return null, please consider processing the abnormal conditions. |
||
44 | * @return BaseBlameableQuery |
||
45 | */ |
||
46 | 4 | public function getUsername() |
|
56 | |||
57 | /** |
||
58 | * Create or get username. |
||
59 | * @param $username |
||
60 | * @return null|Username |
||
61 | */ |
||
62 | 4 | public function createUsername($username) |
|
63 | { |
||
64 | 4 | if (!$this->hasEnabledUsername()) { |
|
65 | return null; |
||
66 | } |
||
67 | 4 | $usernameClass = $this->usernameClass; |
|
68 | 4 | $model = $usernameClass::findOne($this->getGUID()); |
|
69 | 4 | if (!$model) { |
|
70 | 4 | $model = $this->create($usernameClass); |
|
71 | 4 | $model->setGUID($this->getGUID()); |
|
72 | 4 | } |
|
73 | 4 | $model->content = $username; |
|
74 | 4 | return $model; |
|
75 | } |
||
76 | |||
77 | /** |
||
78 | * Set username. |
||
79 | * @param string|Username $username |
||
80 | * @return bool |
||
81 | */ |
||
82 | 2 | public function setUsername($username = null) |
|
83 | { |
||
84 | 2 | if ($username === null && ($model = $this->getUsername()->one())) { |
|
85 | 1 | return $model->delete() > 0; |
|
86 | } |
||
87 | 1 | if ($username instanceof Username) { |
|
88 | $username = $username->content; |
||
89 | } |
||
90 | 1 | $model = $this->createUsername($username); |
|
91 | 1 | return $model->save(); |
|
92 | } |
||
93 | |||
94 | /** |
||
95 | * Remove username. |
||
96 | * @return bool |
||
97 | */ |
||
98 | 1 | public function removeUsername() |
|
102 | } |
||
103 |
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.