diff --git a/src/Controller/StarshipApiController.php b/src/Controller/StarshipApiController.php index c5cc075..472723c 100644 --- a/src/Controller/StarshipApiController.php +++ b/src/Controller/StarshipApiController.php @@ -5,15 +5,28 @@ namespace App\Controller; use App\Repository\StarshipRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Routing\Attribute\Route; +#[Route('/api/starships')] class StarshipApiController extends AbstractController { - #[Route('/api/starships', name: 'starships')] + #[Route('', name: 'starships', methods: ['GET'])] public function getCollection(StarshipRepository $starshipRepository): Response { $starships = $starshipRepository->findAll(); return $this->json($starships); } + + #[Route('/{id<\d+>}', name: 'starship', methods: ['GET'])] + public function get(StarshipRepository $starshipRepository, int $id): Response + { + $starship = $starshipRepository->findOne($id); + if (null === $starship) { + throw $this->createNotFoundException('No starship found for id '.$id); + } + + return $this->json($starship); + } } diff --git a/src/Model/Starship.php b/src/Model/Starship.php index 4ef72b5..8d9fb2a 100644 --- a/src/Model/Starship.php +++ b/src/Model/Starship.php @@ -5,7 +5,7 @@ namespace App\Model; class Starship { public function __construct( - private string $id, + private int $id, private string $name, private string $class, private string $captain, @@ -23,7 +23,7 @@ class Starship return $this->class; } - public function getId(): string + public function getId(): int { return $this->id; } diff --git a/src/Repository/StarshipRepository.php b/src/Repository/StarshipRepository.php index 5f3b436..50381ac 100644 --- a/src/Repository/StarshipRepository.php +++ b/src/Repository/StarshipRepository.php @@ -24,4 +24,14 @@ class StarshipRepository ), ]; } + + public function findOne(int $id): ?Starship + { + foreach ($this->findAll() as $starship) { + if ($starship->getId() === $id) { + return $starship; + } + } + return null; + } }