stl_test/app/Http/Controllers/HoldController.php

65 lines
1.8 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Exceptions\HoldNotAvailableException;
use App\Exceptions\SlotCapacityExceededException;
use App\Models\Hold;
use App\Models\Slot;
use App\Services\SlotService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class HoldController extends Controller
{
public function __construct(
private readonly SlotService $slotService,
) {
}
public function store(Slot $slot): JsonResponse
{
$idempotencyKey = request()->header('X-Idempotency-Key');
try {
$hold = $this->slotService->createHold($slot, $idempotencyKey);
} catch (SlotCapacityExceededException $exception) {
return response()->json([
'message' => $exception->getMessage()
], Response::HTTP_CONFLICT);
}
return response()->json($this->holdPayload($hold), Response::HTTP_CREATED);
}
public function confirm(Hold $hold): JsonResponse
{
try {
$hold = $this->slotService->confirmHold($hold);
} catch (HoldNotAvailableException $exception) {
return response()->json([
'message' => $exception->getMessage()
], Response::HTTP_CONFLICT);
}
return response()->json($this->holdPayload($hold));
}
public function destroy(Hold $hold): JsonResponse
{
$hold = $this->slotService->cancelHold($hold);
return response()->json($this->holdPayload($hold));
}
private function holdPayload(Hold $hold): array
{
return [
'id' => $hold->id,
'slot_id' => $hold->slot_id,
'status' => $hold->status,
'expires_at' => $hold->expires_at->toIso8601String(),
];
}
}