Add method to return single ship, as well as matching route.
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user