Newer
Older
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
<?php
namespace App\Shared\Abstraction;
use App\Shared\Collection\ValidationErrorCollection;
use App\Shared\DtoFactory\ValidateErrorDtoFactory;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
abstract class AbstractRequest
{
/**
* активация автовалидации
* перезаписать на false для отключение автовалидации
*/
protected bool $autoValidate = true;
public function __construct(
protected ValidatorInterface $validator,
protected readonly ValidateErrorDtoFactory $errorDtoFactory
) {
$this->populate();
if ($this->autoValidate) {
$this->validate();
}
}
protected function populate(): void
{
foreach ($this->getRequest()->toArray() as $property => $value) {
if (property_exists($this, $property)) {
$this->{$property} = $value;
}
}
}
public function validate(): void
{
$errors = $this->validator->validate($this);
$messages = new ValidationErrorCollection();
foreach ($errors as $error) {
$messages->add($this->errorDtoFactory->create($error));
}
if ($messages->count() > 0) {
$response = new JsonResponse($messages, 422);
$response->send();
throw new ValidatorException('Validation failed');
}
}
public function getRequest(): Request
{
return Request::createFromGlobals();
}
}