/**
  * Recursive method that pops the next leg off the array of legs to find the first reachable connecting service.
  *
  * Once found the method calls itself again to do the next leg until there are no more legs left.
  *
  * @param  Leg $previousLeg
  * @param  TransferPatternLeg[] $transferLegs
  * @param  string $destination
  * @param  Leg[] $legs
  * @return Journey
  * @throws PlanningException
  */
 private function getJourneyAfter(Leg $previousLeg, array $transferLegs, $destination, array &$legs)
 {
     $transferTime = 0;
     $currentTransferLeg = array_shift($transferLegs);
     // if we've run out of legs to scan maybe there is a transfer at the end
     if ($currentTransferLeg === null) {
         $legs[] = $this->getTransfer($previousLeg->getDestination(), $destination, $previousLeg->getArrivalTime());
         return new Journey($legs);
     }
     // if these connections aren't linked, we might need a non-timetable connection to link us
     if ($previousLeg->getDestination() !== $currentTransferLeg->getOrigin()) {
         $transfer = $this->getTransfer($previousLeg->getDestination(), $currentTransferLeg->getOrigin(), $previousLeg->getArrivalTime());
         $legs[] = $transfer;
         $transferTime = $transfer->getDuration();
     }
     /** @var Leg $leg */
     foreach ($currentTransferLeg->getLegs() as $leg) {
         if ($previousLeg->getArrivalTime() + $transferTime + $this->getInterchange($leg->getOrigin()) <= $leg->getDepartureTime()) {
             $legs[] = $leg;
             if ($leg->getDestination() === $destination) {
                 return new Journey($legs);
             } else {
                 return $this->getJourneyAfter($leg, $transferLegs, $destination, $legs);
             }
         }
     }
     throw new PlanningException("Ran out of connections before reaching the destination");
 }
 /**
  * @param Leg $leg
  * @return stdClass
  */
 private function getLeg(Leg $leg)
 {
     $json = new stdClass();
     $json->mode = strtolower($leg->getMode());
     if ($leg->isTransfer()) {
         $json->origin = $leg->getOrigin();
         $json->destination = $leg->getDestination();
         $json->duration = $this->getTime($leg->getDuration());
         return $json;
     }
     $json->service = $leg->getService();
     $json->operator = $leg->getOperator();
     $json->callingPoints = [$this->getCallingPoint($leg->getOrigin(), $leg->getDepartureTime())];
     foreach ($leg->getConnections() as $c) {
         $json->callingPoints[] = $this->getCallingPoint($c->getDestination(), $c->getArrivalTime());
     }
     return $json;
 }