-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadRequestHandler.php
More file actions
49 lines (38 loc) · 1.63 KB
/
ReadRequestHandler.php
File metadata and controls
49 lines (38 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
declare(strict_types=1);
namespace Chubbyphp\Api\RequestHandler;
use Chubbyphp\Api\Dto\Model\ModelResponseInterface;
use Chubbyphp\Api\Parsing\ParsingInterface;
use Chubbyphp\Api\Repository\RepositoryInterface;
use Chubbyphp\DecodeEncode\Encoder\EncoderInterface;
use Chubbyphp\HttpException\HttpException;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Ramsey\Uuid\Uuid;
final class ReadRequestHandler implements RequestHandlerInterface
{
public function __construct(
private readonly ParsingInterface $parsing,
private readonly RepositoryInterface $repository,
private readonly EncoderInterface $encoder,
private readonly ResponseFactoryInterface $responseFactory,
) {}
public function handle(ServerRequestInterface $request): ResponseInterface
{
/** @var string $id */
$id = $request->getAttribute('id');
/** @var string $accept */
$accept = $request->getAttribute('accept');
if (!Uuid::isValid($id) || null === $model = $this->repository->findById($id)) {
throw HttpException::createNotFound();
}
/** @var ModelResponseInterface $modelResponse */
$modelResponse = $this->parsing->getModelResponseSchema($request)->parse($model);
$output = $this->encoder->encode($modelResponse->jsonSerialize(), $accept);
$response = $this->responseFactory->createResponse(200)->withHeader('Content-Type', $accept);
$response->getBody()->write($output);
return $response;
}
}