<?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(); } }