Conditions | 10 |
Paths | 60 |
Total Lines | 58 |
Code Lines | 27 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 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 |
||
75 | private function getShortestPath($source, $target) |
||
76 | { |
||
77 | // array of the best estimates of shortest path to each vertex |
||
78 | $bestEstimates = []; |
||
79 | // array of predecessors for each vertex |
||
80 | $predecessors = []; |
||
81 | // queue of all unoptimized vertices |
||
82 | $queue = new \SplPriorityQueue(); |
||
83 | |||
84 | foreach ($this->graph as $vertex => $list) { |
||
85 | $bestEstimates[$vertex] = \INF; // set initial distance to "infinity" |
||
86 | $predecessors[$vertex] = null; // no known predecessors yet |
||
87 | foreach ($list as $w => $cost) { |
||
88 | // use the edge cost as the priority |
||
89 | $queue->insert($w, $cost); |
||
90 | } |
||
91 | } |
||
92 | |||
93 | // initial distance at source is 0 |
||
94 | $bestEstimates[$source] = 0; |
||
95 | |||
96 | while (!$queue->isEmpty()) { |
||
97 | // extract min cost |
||
98 | $u = $queue->extract(); |
||
99 | if (!empty($this->graph[$u])) { |
||
100 | // "relax" each adjacent vertex |
||
101 | foreach ($this->graph[$u] as $vertex => $cost) { |
||
102 | // alternate route length to adjacent neighbor |
||
103 | $alt = $bestEstimates[$u] + $cost; |
||
104 | /** |
||
105 | * if alternate route is shorter: |
||
106 | * - update minimum length to vertex |
||
107 | * - add neighbor to predecessors for vertex |
||
108 | */ |
||
109 | if ($alt < $bestEstimates[$vertex]) { |
||
110 | $bestEstimates[$vertex] = $alt; |
||
111 | $predecessors[$vertex] = $u; |
||
112 | |||
113 | $queue->insert($vertex, $cost); |
||
114 | } |
||
115 | } |
||
116 | } |
||
117 | } |
||
118 | |||
119 | // we can now find the shortest path using reverse iteration |
||
120 | $path = []; |
||
121 | $u = $target; |
||
122 | while (isset($predecessors[$u]) && $predecessors[$u]) { |
||
123 | $path[] = $u; |
||
124 | $u = $predecessors[$u]; |
||
125 | } |
||
126 | |||
127 | if (!$path) { |
||
|
|||
128 | return []; |
||
129 | } |
||
130 | |||
131 | return array_reverse(array_merge($path, [$source])); |
||
132 | } |
||
133 | |||
164 |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.