Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

We refactored the solve method to make it cleaner, splitting the method

with other 2 submethods. We can now take a look at phploc because we
are approaching an almost final version of the library.
  • Loading branch information...
commit b42c891dbd7b15e2edb0311928f1bfda8f2f7f0a 1 parent 3ebd3e7
@odino authored
Showing with 52 additions and 24 deletions.
  1. +52 −24 src/Osidays/Algorithm/ShortestPath/Dijkstra.php
View
76 src/Osidays/Algorithm/ShortestPath/Dijkstra.php
@@ -48,34 +48,12 @@ public function __construct(Vertex $from, Vertex $to)
*/
public function solve()
{
- $path = array();
- $vertex = $this->getEndingVertex();
$this->calculatePotentials(
$this->getStartingVertex(),
$this->getEndingVertex()
);
- while ($vertex != $this->getStartingVertex()) {
- if (!$vertex) {
- return null;
- }
-
- if ($vertex->getPotential() < 0) {
- $message = sprintf(
- "%s's algorithm does not support negatively-connected vertices",
- __CLASS__
- );
-
- throw new \LogicException($message);
- }
-
- $path[] = $vertex;
- $vertex = $vertex->getVertexGivingPotential();
- }
-
- $path[] = $this->getStartingVertex();
-
- return array_reverse($path);
+ return $this->calculatePath();
}
/**
@@ -102,11 +80,61 @@ protected function assignConnectedPotentials(Vertex $vertex)
}
}
+ /**
+ * Calculates an array of vertices connecting the starting point of the
+ * algorithm to the ending point.
+ *
+ * @return array|null
+ */
+ protected function calculatePath()
+ {
+ $vertex = $this->getEndingVertex();
+ $path = array();
+
+ while ($vertex != $this->getStartingVertex()) {
+ if (!$vertex) {
+ return null;
+ }
+
+ $this->checkPotential($vertex);
+ $path[] = $vertex;
+ $vertex = $vertex->getVertexGivingPotential();
+ }
+
+ $path[] = $this->getStartingVertex();
+
+ return array_reverse($path);
+ }
+
+ /**
+ * Sets the potentials to each Vertex between $from and $to.
+ *
+ * @param Vertex $from
+ * @param Vertex $to
+ */
protected function calculatePotentials(Vertex $from, Vertex $to)
{
$from->setPotential(0);
$this->assignConnectedPotentials($from);
- }
+ }
+
+ /**
+ * Checks that the given $vertex has non-negative potential.
+ *
+ * @param Vertex $vertex
+ * @throws \LogicException
+ */
+ protected function checkPotential(Vertex $vertex)
+ {
+ if ($vertex->getPotential() < 0) {
+ $message = sprintf(
+ "%s's algorithm does not support negatively-connected vertices",
+ __CLASS__
+ );
+
+ throw new \LogicException($message);
+ }
+ }
/**
* Returns the destination of the path.
Please sign in to comment.
Something went wrong with that request. Please try again.