Commit 3d21d6ed by Lech Sawon

dto in controller

parent 202320dd
......@@ -21,6 +21,7 @@ services:
- '../src/Kernel.php'
- '../src/Tests/'
- '../src/Service/'
- '../src/Dto'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
......
......@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Controller\Api;
use App\Dto\AddReservationDto;
use App\Entity\Reservation;
use App\Entity\Room;
use App\Repository\RoomRepository;
......@@ -12,6 +13,7 @@ use App\Service\Reservation\AddReservation;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;
final class AddReservationController
{
......@@ -21,12 +23,25 @@ final class AddReservationController
public function __invoke(
Request $request,
AddReservation $addReservation,
RoomRepository $roomRepository
RoomRepository $roomRepository,
ValidatorInterface $validator
): JsonResponse {
$array = json_decode($request->getContent(), true);
//walidacjia danych przy pomocy DTO i symfony validator
$dto = AddReservationDto::createFromArray($array);
$errors = $validator->validate($dto);
if (count($errors) > 0) {
$errorsString = (string) $errors;
return new JsonResponse($errorsString);
}
// ten kod mógłby być bardziej elegancki, ale jako przykład jest good enough
$array = json_decode($request->getContent(), true);
$room = $roomRepository->find($array['roomId']);
// moglibyśmy np przekazać DTO do serwisu i tam zająć się znalezieniem Room i zapisemr
$room = $roomRepository->find($dto->getRoomId());
if (!$room instanceof Room) {
//było by lepiej użyć własnego exception
......@@ -37,8 +52,8 @@ final class AddReservationController
$reservation
->setRoom($room)
->setDateFrom(new \DateTime($array['dateFrom']))
->setDateEnd(new \DateTime($array['dateTo']))
->setDateFrom(new \DateTime($dto->getDateFrom()))
->setDateEnd(new \DateTime($dto->getDateFrom()))
;
$addReservation->add($reservation);
......
<?php
declare(strict_types=1);
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
final class AddReservationDto
{
/**
* @Assert\GreaterThan(0)
*/
private int $roomId;
private string $dateFrom;
private string $dateTo;
public function __construct(int $roomId, string $dateFrom, string $dateTo)
{
$this->roomId = $roomId;
$this->dateFrom = $dateFrom;
$this->dateTo = $dateTo;
}
public function getRoomId(): int
{
return $this->roomId;
}
public function getDateFrom(): string
{
return $this->dateFrom;
}
public function getDateTo(): string
{
return $this->dateTo;
}
public static function createFromArray(array $array): self
{
return new self(
$array['roomId'],
$array['dateFrom'],
$array['dateTo']
);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment