public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if (null === ($trackingId = $request->getAttribute('trackingId'))) {
         return new EmptyResponse(404);
     }
     $cargoData = $request->getParsedBody();
     if (!isset($cargoData['legs']) || !is_array($cargoData['legs'])) {
         throw new \InvalidArgumentException("Missing legs for cargo");
     }
     $routeCandidate = new RouteCandidateDto();
     $routeCandidate->setLegs($this->toLegDtosFromData($cargoData['legs']));
     try {
         $this->bookingService->assignCargoToRoute($trackingId, $routeCandidate);
         $cargoRoutingDto = $this->bookingService->loadCargoForRouting($trackingId);
         return new JsonResponse($cargoRoutingDto->getArrayCopy());
     } catch (CargoNotFoundException $e) {
         return new EmptyResponse(404);
     }
 }
 /**
  * @test
  */
 public function it_assigns_cargo_to_route()
 {
     $trackingId = $this->bookingService->bookNewCargo('USNYC', 'DEHAM');
     $routeCandidates = $this->bookingService->requestPossibleRoutesForCargo($trackingId);
     $this->bookingService->assignCargoToRoute($trackingId, $routeCandidates[0]);
     $cargo = $this->cargoRepository->get(TrackingId::fromString($trackingId));
     $legs = $cargo->itinerary()->legs();
     $this->assertEquals(1, count($legs));
     $this->assertEquals('USNYC', $legs[0]->loadLocation());
     $this->assertEquals('DEHAM', $legs[0]->unloadLocation());
 }