-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdateRequestHandler.php
More file actions
72 lines (56 loc) · 2.55 KB
/
UpdateRequestHandler.php
File metadata and controls
72 lines (56 loc) · 2.55 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace Chubbyphp\Api\RequestHandler;
use Chubbyphp\Api\Dto\Model\ModelRequestInterface as ModelModelRequestInterface;
use Chubbyphp\Api\Dto\Model\ModelResponseInterface;
use Chubbyphp\Api\Parsing\ParsingInterface;
use Chubbyphp\Api\Repository\RepositoryInterface;
use Chubbyphp\DecodeEncode\Decoder\DecoderInterface;
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;
use Ramsey\Uuid\Uuid;
final class UpdateRequestHandler implements RequestHandlerInterface
{
public function __construct(
private readonly DecoderInterface $decoder,
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');
/** @var string $contentType */
$contentType = $request->getAttribute('contentType');
if (!Uuid::isValid($id) || null === $model = $this->repository->findById($id)) {
throw HttpException::createNotFound();
}
$input = $this->decoder->decode((string) $request->getBody(), $contentType);
try {
/** @var ModelModelRequestInterface $modelRequest */
$modelRequest = $this->parsing->getModelRequestSchema($request)->parse($input);
} catch (ErrorsException $e) {
throw HttpException::createUnprocessableEntity([
'invalidParameters' => $e->errors->toApiProblemInvalidParameters(),
]);
}
$model = $modelRequest->updateModel($model);
$this->repository->persist($model);
$this->repository->flush();
/** @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;
}
}