Add method to return single ship, as well as matching route.

This commit is contained in:
Krzysztof Płaczek
2024-10-18 12:10:06 +02:00
parent 1a2b801cd9
commit 2eccc51981
3 changed files with 26 additions and 3 deletions

View File

@@ -5,15 +5,28 @@ namespace App\Controller;
use App\Repository\StarshipRepository; use App\Repository\StarshipRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route; use Symfony\Component\Routing\Attribute\Route;
#[Route('/api/starships')]
class StarshipApiController extends AbstractController class StarshipApiController extends AbstractController
{ {
#[Route('/api/starships', name: 'starships')] #[Route('', name: 'starships', methods: ['GET'])]
public function getCollection(StarshipRepository $starshipRepository): Response public function getCollection(StarshipRepository $starshipRepository): Response
{ {
$starships = $starshipRepository->findAll(); $starships = $starshipRepository->findAll();
return $this->json($starships); 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);
}
} }

View File

@@ -5,7 +5,7 @@ namespace App\Model;
class Starship class Starship
{ {
public function __construct( public function __construct(
private string $id, private int $id,
private string $name, private string $name,
private string $class, private string $class,
private string $captain, private string $captain,
@@ -23,7 +23,7 @@ class Starship
return $this->class; return $this->class;
} }
public function getId(): string public function getId(): int
{ {
return $this->id; return $this->id;
} }

View File

@@ -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;
}
} }