-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListRequestHandler.php
More file actions
58 lines (45 loc) · 2.07 KB
/
ListRequestHandler.php
File metadata and controls
58 lines (45 loc) · 2.07 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
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
namespace Chubbyphp\Api\RequestHandler;
use Chubbyphp\Api\Dto\Collection\CollectionRequestInterface;
use Chubbyphp\Api\Dto\Collection\CollectionResponseInterface;
use Chubbyphp\Api\Parsing\ParsingInterface;
use Chubbyphp\Api\Repository\RepositoryInterface;
use Chubbyphp\DecodeEncode\Encoder\EncoderInterface;
use Chubbyphp\HttpException\HttpException;
use Chubbyphp\Parsing\ErrorsException;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class ListRequestHandler 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 $accept */
$accept = $request->getAttribute('accept');
$input = $request->getQueryParams();
try {
/** @var CollectionRequestInterface $collectionRequest */
$collectionRequest = $this->parsing->getCollectionRequestSchema($request)->parse($input);
} catch (ErrorsException $e) {
throw HttpException::createBadRequest([
'invalidParameters' => $e->errors->toApiProblemInvalidParameters(),
]);
}
$collection = $collectionRequest->createCollection();
$this->repository->resolveCollection($collection);
/** @var CollectionResponseInterface $collectionResponse */
$collectionResponse = $this->parsing->getCollectionResponseSchema($request)->parse($collection);
$output = $this->encoder->encode($collectionResponse->jsonSerialize(), $accept);
$response = $this->responseFactory->createResponse(200)->withHeader('Content-Type', $accept);
$response->getBody()->write($output);
return $response;
}
}