<?php
namespace App\Resource\Error;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class errorDisplay {
private $validator;
private $request;
public function __construct(array $request = null, ValidatorInterface $validator = null) {
if ($validator) {
$this->validator = $validator;
$this->request = $request;
}
}
/**
* @param ConstraintViolationListInterface $errors
* @return JsonResponse
*/
public function show(ConstraintViolationListInterface $errors) {
$errorDisplay = [];
foreach ($errors as $error) {
$errorDisplay[$error->getPropertyPath()] = $error->getMessage();
}
return new JsonResponse([
'success' => false,
'message' => 'datos incorrectos',
'messageData' => $errorDisplay
], Response::HTTP_BAD_REQUEST);
}
/**
* @param $val
* @param $entity
* @param string $method
* @param array $out
* @param bool $type
* @return JsonResponse | array
*/
public function paramValidate($val, $entity, $method = 'post', $out = [], $type = true) {
$obj = new $entity;
foreach ($val as $key) {
$b = "set" . ucfirst($key);
$obj->$b($this->request[$key]);
array_push($out, $key);
}
if (count($b = $this->validator->validate($obj)) > 0) {
if (!is_bool($c = $this->validateElements($b, $out))) {
if ($type) {
return new JsonResponse([
'success' => false,
'data' => 'Datos no validos',
'msg' => 'Datos no validos',
'message' => 'Datos no validos',
'messageData' => $c
], Response::HTTP_BAD_REQUEST);
} else {
return [
'success' => false,
'data' => 'Datos no validos',
'msg' => 'Datos no validos',
'message' => 'Datos no validos',
'messageData' => $c
];
}
}
}
return $obj;
}
/**
* @param ConstraintViolationListInterface $obj
* @param array $out
* @param array $errorDisplay
* @return array|bool
*/
private function validateElements(ConstraintViolationListInterface $obj, $out, $errorDisplay = []) {
foreach ($obj as $error) {
if (in_array($error->getpropertyPath(), $out)) {
$errorDisplay[$error->getPropertyPath()] = $error->getMessage();
}
}
if (count($errorDisplay) == 0) return true;
return $errorDisplay;
}
}