Conditions | 10 |
Paths | 23 |
Total Lines | 61 |
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 |
||
20 | public static function buildLink(HasLinks $model, string $routePart, Router $router, string $method = null) |
||
21 | { |
||
22 | $routeStub = $model->getRouteName(); |
||
23 | |||
24 | if ($routeStub === null) { |
||
25 | return false; |
||
26 | } |
||
27 | |||
28 | if (!$model->getKeyName()) { |
||
|
|||
29 | return false; |
||
30 | } |
||
31 | |||
32 | // Make the route name, and check if it exists. |
||
33 | $routeName = "$routeStub.$routePart"; |
||
34 | |||
35 | if (!($route = $router->getRoutes()->getByName($routeName))) { |
||
36 | return false; |
||
37 | } |
||
38 | |||
39 | // Get any params needed to build the URL. |
||
40 | $params = []; |
||
41 | switch ($routePart) { |
||
42 | case 'destroy': |
||
43 | case 'update': |
||
44 | case 'show': |
||
45 | $params = [$model->getRouteKey() => $model->getAttribute((string)$model->getKeyName())]; |
||
46 | break; |
||
47 | case 'show.extra': |
||
48 | $params = [ |
||
49 | $model->getRouteKey() => $model->getAttribute((string)$model->getKeyName()), |
||
50 | 'extra' => $method |
||
51 | ]; |
||
52 | break; |
||
53 | } |
||
54 | |||
55 | // Get the methods applicable to the route, ignoring HEAD and PATCH. |
||
56 | $methods = collect($route->methods()); |
||
57 | $methods = $methods->filter(static function ($item) { |
||
58 | return !in_array($item, ['HEAD', 'PATCH']); |
||
59 | })->map(static function ($str) { |
||
60 | return strtolower($str); |
||
61 | }); |
||
62 | |||
63 | // If there's only 1, return just that, otherwise, return an array. |
||
64 | if ($methods->count() === 1) { |
||
65 | $methods = $methods->first(); |
||
66 | } |
||
67 | |||
68 | // Add! |
||
69 | try { |
||
70 | return [ |
||
71 | 'method' => $methods, |
||
72 | 'href' => [ |
||
73 | 'relative' => route($routeName, $params, false), |
||
74 | 'absolute' => route($routeName, $params, true) |
||
75 | ] |
||
76 | ]; |
||
77 | } catch (UrlGenerationException $ex) { |
||
78 | return false; |
||
79 | } |
||
80 | } |
||
81 | } |
||
82 |
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: