Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 23 | trait SetterTrait |
||
| 24 | { |
||
| 25 | /** |
||
| 26 | * Set permission. |
||
| 27 | * @param string $name |
||
| 28 | * @param string $description |
||
| 29 | * @return Item |
||
| 30 | */ |
||
| 31 | 13 | public function setPermission($name, $description = null) |
|
| 41 | |||
| 42 | /** |
||
| 43 | * Set role. |
||
| 44 | * @param string $name |
||
| 45 | * @param string $description |
||
| 46 | * @return Item |
||
| 47 | */ |
||
| 48 | 13 | public function setRole($name, $description = null) |
|
| 58 | |||
| 59 | /** |
||
| 60 | * Set child. |
||
| 61 | * @param string|Item $parent |
||
| 62 | * @param string|Item $child |
||
| 63 | * @return bool |
||
| 64 | */ |
||
| 65 | 13 | public function setChild($parent, $child) |
|
| 87 | |||
| 88 | /** |
||
| 89 | * Assigns an item (role or permission) to a user. |
||
| 90 | * @param string|Item $item |
||
| 91 | * @param string|integer $userId the user ID (see [[\yii\web\User::id]]) |
||
| 92 | * @throws \Exception when given wrong item name |
||
| 93 | * @return Assignment|null the assignment object or `null` when assignment was not found by name |
||
| 94 | */ |
||
| 95 | 26 | public function setAssignment($item, $userId) |
|
| 113 | |||
| 114 | 26 | protected function findItem($name, $description = null) |
|
| 115 | { |
||
| 116 | 26 | $item = $this->getItem($name); |
|
| 117 | 26 | if ($item) { |
|
| 118 | 26 | return $item; |
|
| 119 | } |
||
| 120 | if (strncmp($name, 'deny:', 5) === 0) { |
||
| 121 | return $this->setPermission($name, $description); |
||
| 122 | } |
||
| 123 | |||
| 124 | throw new InvalidConfigException("Unknown item:$name at findItem"); |
||
| 125 | } |
||
| 126 | |||
| 127 | /** |
||
| 128 | * Assigns items to a user. |
||
| 129 | * @param string|array $items |
||
| 130 | * @param string|integer $userId |
||
| 131 | */ |
||
| 132 | 10 | public function setAssignments($items, $userId) |
|
| 141 | |||
| 142 | /** |
||
| 143 | * Returns all assignments in the system. |
||
| 144 | * @return array |
||
| 145 | */ |
||
| 146 | public function getAllAssignments() |
||
| 150 | |||
| 151 | /** |
||
| 152 | * Returns all items in the system. |
||
| 153 | * @return array |
||
| 154 | */ |
||
| 155 | 26 | public function getAllItems() |
|
| 159 | } |
||
| 160 |
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
Idableprovides a methodequalsIdthat 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.