Commit c1c9ba16 by Lech Sawon

deserialize with symfony serializer

parent 3d21d6ed
......@@ -13,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\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
final class AddReservationController
......@@ -21,25 +22,26 @@ final class AddReservationController
* @Route("/api/reservation", name="api_add_reservation", methods={"POST"})
*/
public function __invoke(
// stanowczo za dużo zależności. w mojej ocenie 3 to żółte światło 5 czerwone
Request $request,
AddReservation $addReservation,
RoomRepository $roomRepository,
ValidatorInterface $validator
ValidatorInterface $validator,
SerializerInterface $serializer
): JsonResponse {
$array = json_decode($request->getContent(), true);
//walidacjia danych przy pomocy DTO i symfony validator
$dto = AddReservationDto::createFromArray($array);
$dto = $serializer->deserialize($request->getContent(), AddReservationDto::class, 'json');
$errors = $validator->validate($dto);
if (count($errors) > 0) {
// zwracane błędy powinny być bardziej czytelne, teraz jest to uproszczone
$errorsString = (string) $errors;
return new JsonResponse($errorsString);
}
// ten kod mógłby być bardziej elegancki, ale jako przykład jest good enough
// moglibyśmy np przekazać DTO do serwisu i tam zająć się znalezieniem Room i zapisemr
// moglibyśmy np przekazać DTO do serwisu i tam zająć się znalezieniem Room i zapisem
// w ramach ćwiczeń można przeprowadzić refactoring przenoszący to co poniżej do serwisu
$room = $roomRepository->find($dto->getRoomId());
......
......@@ -5,16 +5,24 @@ declare(strict_types=1);
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Serializer\Annotation\SerializedName;
final class AddReservationDto
{
/**
* @Assert\GreaterThan(0)
* @SerializedName("room_id")
*/
private int $roomId;
/**
* @SerializedName("date_from")
*/
private string $dateFrom;
/**
* @SerializedName("date_to")
*/
private string $dateTo;
public function __construct(int $roomId, string $dateFrom, string $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