| Conditions | 8 |
| Paths | 14 |
| Total Lines | 51 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
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:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 128 | private function buildLink(HasLinks $model, string $routePart, Router $router) |
||
| 129 | { |
||
| 130 | $routeStub = $model->getRouteName(); |
||
| 131 | |||
| 132 | if (!$routeStub) { |
||
| 133 | return false; |
||
| 134 | } |
||
| 135 | |||
| 136 | // Make the route name, and check if it exists. |
||
| 137 | $routeName = "$routeStub.$routePart"; |
||
| 138 | |||
| 139 | if (!$router->has($routeName)) { |
||
| 140 | return false; |
||
| 141 | } |
||
| 142 | |||
| 143 | // Get any params needed to build the URL. |
||
| 144 | $params = []; |
||
| 145 | switch ($routePart) { |
||
| 146 | case 'destroy': |
||
| 147 | case 'update': |
||
| 148 | case 'show': |
||
| 149 | $params = [$this->getRouteKey() => $this->id]; |
||
| 150 | break; |
||
| 151 | } |
||
| 152 | |||
| 153 | // Get the route. |
||
| 154 | $route = $router->getRoutes()->getByName($routeName); |
||
| 155 | |||
| 156 | if (!$route) { |
||
| 157 | return false; |
||
| 158 | } |
||
| 159 | |||
| 160 | // Get the methods applicable to the route, ignoring HEAD and PATCH. |
||
| 161 | $methods = collect($route->methods()); |
||
| 162 | $methods = $methods->filter(static function ($item) { |
||
| 163 | return !in_array($item, ['HEAD', 'PATCH']); |
||
| 164 | })->map(static function ($str) { |
||
| 165 | return strtolower($str); |
||
| 166 | }); |
||
| 167 | |||
| 168 | // If there's only 1, return just that, otherwise, return an array. |
||
| 169 | if ($methods->count() === 1) { |
||
| 170 | $methods = $methods->first(); |
||
| 171 | } |
||
| 172 | |||
| 173 | // Add! |
||
| 174 | return [ |
||
| 175 | 'method' => $methods, |
||
| 176 | 'href' => route($routeName, $params, false) |
||
| 177 | ]; |
||
| 178 | } |
||
| 179 | |||
| 193 |
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.