Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
21 / 21 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| RecordExpenseController | |
100.00% |
21 / 21 |
|
100.00% |
2 / 2 |
6 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| record | |
100.00% |
20 / 20 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Expense\Infrastructure\Controllers; |
| 6 | |
| 7 | use App\Expense\Application\Command\RecordExpenseCommand; |
| 8 | use App\Expense\Application\Command\RecordExpenseHandler; |
| 9 | use App\Identity\Infrastructure\Http\ResolvesAuthenticatedUser; |
| 10 | use App\Shared\Infrastructure\Http\ReadsJsonPayload; |
| 11 | use App\Trip\Domain\Exceptions\TripAccessDenied; |
| 12 | use App\Trip\Domain\Exceptions\TripNotFound; |
| 13 | use App\Trip\Infrastructure\Http\ValidatesTripId; |
| 14 | use InvalidArgumentException; |
| 15 | use OpenApi\Attributes as OA; |
| 16 | use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
| 17 | use Symfony\Component\HttpFoundation\JsonResponse; |
| 18 | use Symfony\Component\HttpFoundation\Request; |
| 19 | use Symfony\Component\Routing\Attribute\Route; |
| 20 | |
| 21 | #[OA\Tag(name: 'Expenses')] |
| 22 | class RecordExpenseController extends AbstractController |
| 23 | { |
| 24 | use ReadsJsonPayload; |
| 25 | use ResolvesAuthenticatedUser; |
| 26 | use ValidatesTripId; |
| 27 | |
| 28 | public function __construct( |
| 29 | private readonly RecordExpenseHandler $handler, |
| 30 | ) { |
| 31 | } |
| 32 | |
| 33 | #[Route('/trips/{tripId}/expenses', name: 'expenses_record', methods: ['POST'])] |
| 34 | public function record(string $tripId, Request $request): JsonResponse |
| 35 | { |
| 36 | $securityUser = $this->securityUser(); |
| 37 | |
| 38 | if ($this->parseTripId($tripId) === null) { |
| 39 | return new JsonResponse(['error' => 'Trip not found.'], 404); |
| 40 | } |
| 41 | |
| 42 | try { |
| 43 | $payload = $this->decodeJsonBody($request); |
| 44 | |
| 45 | $expenseId = $this->handler->handle(new RecordExpenseCommand( |
| 46 | tripId: $tripId, |
| 47 | userId: $securityUser->userId(), |
| 48 | amount: $this->intField($payload, 'amount'), |
| 49 | currency: $this->stringField($payload, 'currency'), |
| 50 | category: $this->stringField($payload, 'category'), |
| 51 | description: $this->stringField($payload, 'description'), |
| 52 | spentAt: $this->stringField($payload, 'spentAt'), |
| 53 | )); |
| 54 | } catch (TripNotFound $e) { |
| 55 | return new JsonResponse(['error' => $e->getMessage()], 404); |
| 56 | } catch (TripAccessDenied $e) { |
| 57 | return new JsonResponse(['error' => $e->getMessage()], 403); |
| 58 | } catch (InvalidArgumentException $e) { |
| 59 | return new JsonResponse(['error' => $e->getMessage()], 400); |
| 60 | } |
| 61 | |
| 62 | return new JsonResponse(['id' => $expenseId->value()], 201); |
| 63 | } |
| 64 | } |