<?php
namespace App\Service\Validator;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class ValidatorService
{
private $validator;
private $requestStack;
public function __construct(
ValidatorInterface $validator,
RequestStack $requestStack,
protected TranslatorInterface $translator,
)
{
$this->validator = $validator;
$this->requestStack = $requestStack;
}
public function validate($constraints)
{
if (!empty($this->requestStack->getCurrentRequest()->getContent())) {
$input = json_decode($this->requestStack->getCurrentRequest()->getContent(), true);
} else {
$input = $this->requestStack->getCurrentRequest()->request->all();
}
if (empty($input)) {
$input = [];
}
$validationResult = $this->validator->validate($input, $constraints);
foreach ($validationResult as $violation) {
throw new MessageException($violation->getPropertyPath(), $violation->getMessage());
}
foreach ($input as $key => $value) {
if (is_string($value))
$input[$key] = trim($value);
}
return $input;
}
public function validateWithoutError($constraints)
{
if (!empty($this->requestStack->getCurrentRequest()->getContent())) {
$input = json_decode($this->requestStack->getCurrentRequest()->getContent(), true);
} else {
$input = $this->requestStack->getCurrentRequest()->request->all();
}
if (empty($input)) {
$input = [];
}
if (isset($input['email'])) {
$email = $input['email'];
$accents = '/&([A-Za-z]{1,2})(grave|acute|circ|cedil|uml|lig);/';
$string_encoded = htmlentities($email, ENT_NOQUOTES, 'UTF-8');
$email = preg_replace($accents, '$1', $string_encoded);
$input['email'] = $email;
}
$validationResult = $this->validator->validate($input, $constraints);
foreach ($validationResult as $violation) {
$message = $violation->getMessage();
if ($violation->getMessageTemplate() == 'This field is missing.') {
$message = $this->translator->trans('api.fillRequiredField');
}
throw new MessageException('', $message);
}
foreach ($input as $key => $value) {
if (is_string($value))
$input[$key] = trim($value);
}
return $input;
}
}