-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathRequestValidator.php
More file actions
84 lines (69 loc) · 2.63 KB
/
Copy pathRequestValidator.php
File metadata and controls
84 lines (69 loc) · 2.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
declare(strict_types=1);
namespace PhpList\RestBundle\Common\Validator;
use PhpList\RestBundle\Common\Request\RequestInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Throwable;
class RequestValidator
{
public function __construct(
private readonly DenormalizerInterface $serializer,
private readonly ValidatorInterface $validator
) {
}
public function validate(Request $request, string $dtoClass, ?callable $beforeValidation = null): RequestInterface
{
try {
$content = $request->getContent();
$body = ($content !== '' && $content !== '0') ? json_decode($content, true, 512, JSON_THROW_ON_ERROR) : [];
} catch (Throwable $e) {
throw new BadRequestHttpException('Invalid JSON: ' . $e->getMessage());
}
$routeParams = $request->attributes->get('_route_params') ?? [];
if (isset($routeParams['listId'])) {
$routeParams['listId'] = (int) $routeParams['listId'];
}
if (isset($routeParams['templateId'])) {
$routeParams['templateId'] = (int) $routeParams['templateId'];
}
$data = array_merge($routeParams, $request->query->all(), $body ?? []);
try {
/** @var RequestInterface $dto */
$dto = $this->serializer->denormalize(
$data,
$dtoClass,
null,
['allow_extra_attributes' => true]
);
} catch (Throwable $e) {
throw new BadRequestHttpException(
'Invalid request data: ' . $e->getMessage() . ' Data: ' . json_encode($data)
);
}
if ($beforeValidation !== null) {
$beforeValidation($dto);
}
return $this->validateDto($dto);
}
public function validateDto(RequestInterface $request): RequestInterface
{
$errors = $this->validator->validate($request);
if (count($errors) > 0) {
$lines = [];
foreach ($errors as $violation) {
$lines[] = sprintf(
'%s: %s',
$violation->getPropertyPath(),
$violation->getMessage()
);
}
$message = implode("\n", $lines);
throw new UnprocessableEntityHttpException($message);
}
return $request;
}
}