|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Action\User; |
| 6 | + |
| 7 | +use App\Domain\User\Service\UserReader; |
| 8 | +use Psr\Http\Message\ResponseInterface; |
| 9 | +use Psr\Http\Message\ServerRequestInterface; |
| 10 | + |
| 11 | +final class UserReadAction |
| 12 | +{ |
| 13 | + private UserReader $userReader; |
| 14 | + |
| 15 | + public function __construct(UserReader $userReader) |
| 16 | + { |
| 17 | + $this->userReader = $userReader; |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Invoke. |
| 22 | + * |
| 23 | + * @param ServerRequestInterface $request The request |
| 24 | + * @param ResponseInterface $response The response |
| 25 | + * @param array<mixed> $args The route arguments |
| 26 | + * |
| 27 | + * @return ResponseInterface The response |
| 28 | + */ |
| 29 | + public function __invoke( |
| 30 | + ServerRequestInterface $request, |
| 31 | + ResponseInterface $response, |
| 32 | + array $args = [] |
| 33 | + ): ResponseInterface { |
| 34 | + // Collect input from the HTTP request |
| 35 | + $userId = (int)$args['id']; |
| 36 | + |
| 37 | + // Invoke the Domain (application service) with inputs and keep the result |
| 38 | + $user = $this->userReader->getUserDetails($userId); |
| 39 | + |
| 40 | + // Transform the result into the JSON representation |
| 41 | + $result = [ |
| 42 | + 'user_id' => $user->id, |
| 43 | + 'username' => $user->username, |
| 44 | + 'first_name' => $user->firstName, |
| 45 | + 'last_name' => $user->lastName, |
| 46 | + 'email' => $user->email, |
| 47 | + ]; |
| 48 | + |
| 49 | + // Build the HTTP response |
| 50 | + $response->getBody()->write((string)json_encode($result)); |
| 51 | + |
| 52 | + return $response->withHeader('Content-Type', 'application/json')->withStatus(200); |
| 53 | + } |
| 54 | +} |
0 commit comments