Created
July 24, 2019 12:04
-
-
Save wapcrazut/03dfc2eda3acad26599588265ab98e4c to your computer and use it in GitHub Desktop.
Symfony 4 Form validation trait, useful for getting errors from form validation and constraints.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Form\Api; | |
use Symfony\Component\Form\FormInterface; | |
use Symfony\Component\Validator\ConstraintViolation; | |
trait FormValidationTrait | |
{ | |
private function getErrorsFromForm(FormInterface $form) | |
{ | |
$errors = array(); | |
foreach ($form->getErrors() as $error) { | |
$errors[$error->getCause()->getPropertyPath()] = [ | |
'message' => $error->getMessage(), | |
'severity' => $this->checkConstraintPayloadSeverity($error->getCause()), | |
'code' => $this->checkConstraintPayloadCode($error->getCause()) | |
]; | |
} | |
foreach ($form->all() as $childForm) { | |
if ($childForm instanceof FormInterface) { | |
if ($childErrors = $this->getErrorsFromForm($childForm)) { | |
$errors = array_merge($errors, $this->getErrorsFromForm($childForm)); | |
} | |
} | |
} | |
return $errors; | |
} | |
private function checkConstraintPayloadSeverity(ConstraintViolation $error) | |
{ | |
$constraint = $error->getConstraint(); | |
return $constraint->payload['severity'] ?? null; | |
} | |
private function checkConstraintPayloadCode(ConstraintViolation $error) | |
{ | |
$constraint = $error->getConstraint(); | |
return $constraint->payload['code'] ?? null; | |
} | |
private function isAllowedToContinue(array $errorCollection) | |
{ | |
if ($errorCollection == null) { | |
return true; | |
} | |
dump($errorCollection); | |
die(); | |
foreach ($errorCollection as $field => $collection) { | |
foreach ($collection as $payload) { | |
$severity = $payload['severity'] ?? null; | |
switch ($severity) { | |
case "critical": | |
return false; | |
break; | |
case "warning": | |
$response = true; | |
break; | |
case "notice": | |
$response = true; | |
break; | |
default: | |
$response = true; | |
break; | |
} | |
} | |
} | |
return $response; | |
} | |
private function simplifyErrors($errorsCollection) | |
{ | |
$simpleErrors = []; | |
foreach ($errorsCollection as $field => $collection) { | |
$message = ''; | |
foreach ($collection as $payload) { | |
$message = $payload['message'] ?? ''; | |
} | |
$simpleErrors[$field] = $message; | |
} | |
return $simpleErrors; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment