Files
myep/src/Service/BookingService.php
T

92 lines
3.2 KiB
PHP

<?php
namespace App\Service;
use App\BusProNet\Model\Room;
use App\Form\Model\BookingCreateDto;
use App\Form\Model\RoomSelectionDto;
use App\Service\TravelDataService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class BookingService
{
public function __construct(
private readonly TravelDataService $travelDataService,
) {
}
public function getOrCreateBookingCreateDto(Request $request): BookingCreateDto
{
$bookingUuid = $request->query->get('uid');
$bookingCreateDto = $request->getSession()->get('booking_create');
// No UID parameter - return existing DTO from session if available
if (null === $bookingUuid && null !== $bookingCreateDto) {
return $bookingCreateDto;
}
// Create a new DTO - we need date_id and hotel_id for this
$dateId = $request->query->getInt('date_id');
$hotelId = $request->query->getInt('hotel_id');
if (0 === $dateId || 0 === $hotelId) {
throw new NotFoundHttpException('Missing date_id or hotel_id parameters');
}
$travelData = $this->travelDataService->getTravelData($dateId, $hotelId);
if (null === $travelData) {
throw new NotFoundHttpException(sprintf('Travel data not found for date ID %d and hotel ID %d', $dateId, $hotelId));
}
$roomsIdsAndQuantities = $this->processRoomQuantities($request);
$availableRooms = $travelData->getAvailableRooms();
$roomSelections = array_map(
fn (Room $room) => $this->createRoomSelection($room, $roomsIdsAndQuantities),
$availableRooms
);
$bookingCreateDto = new BookingCreateDto($travelData, $hotelId);
$bookingCreateDto->roomSelections = $roomSelections;
$this->saveBookingCreateDto($request, $bookingCreateDto);
return $bookingCreateDto;
}
public function saveBookingCreateDto(Request $request, BookingCreateDto $bookingCreateDto): void
{
$request->getSession()->set('booking_create', $bookingCreateDto);
}
private function createRoomSelection(Room $room, array $roomsIdsAndQuantities): RoomSelectionDto
{
$selection = new RoomSelectionDto();
$selection->roomId = $room->id;
$selection->roomLabel = $room->label;
$selection->maxQuantity = $room->available;
$selection->minPax = $room->minPax;
$selection->quantity = $roomsIdsAndQuantities[$room->id] ?? 0;
return $selection;
}
/**
* Extracts room IDs and quantities from the request data.
*
* Processes the 'rooms' parameter from the request to extract room IDs
* as keys and their corresponding quantities as integer values. Filters
* out empty values and converts all quantities to integers.
*
* @param Request $request The HTTP request containing room data
*
* @return array<int, int> Array with room IDs as keys and quantities as values
*/
public function processRoomQuantities(Request $request): array
{
$rooms = $request->request->all('rooms');
return array_map('intval', array_filter($rooms, 'strlen'));
}
}