Skip to content

Instantly share code, notes, and snippets.

@cristianoc72
Last active January 14, 2022 22:07
Show Gist options
  • Save cristianoc72/5845056 to your computer and use it in GitHub Desktop.
Save cristianoc72/5845056 to your computer and use it in GitHub Desktop.
Extract, from a ConstraintViolationsList object, an associative array where the keys are property names and values are error messages. This function was originally created to be used inside a Propel2 project. Anyway, it can be used in every project following the PSR-0 and using the Symfony Validator Component.
<?php
/**
* This function was originally created to be used inside a Propel2 project.
* Anyway, it can be used in every project following the PSR-0 and using the Symfony Validator Component.
*
* @see http://symfony.com/doc/current/book/validation.html
* @see https://github.com/propelorm/Propel2/blob/master/documentation/behaviors/validate.markdown
*/
use Symfony\Component\Validator\ConstraintViolationList;
/**
* Extract, from a ConstraintViolationList object, an associative array as follow:
* <code>
* array(
* 'property1.1' => array('message1.1', 'message1.2'),
* 'property1.2' => array('message2')
* ........
* )
* </code>
* with the possibility to filter a given property path.
*
* @param $violationsList ConstraintViolationList object
* @param string $propertyPath The name of the property to filter
*
* @return array
*/
function violations_to_array(ConstraintViolationList $violationsList, $propertyPath = null)
{
$output = array();
foreach ($violationsList as $violation) {
$output[$violation->getPropertyPath()][] = $violation->getMessage();
}
if (null !== $propertyPath) {
if (array_key_exists($propertyPath, $output)) {
$output = array($propertyPath => $output[$propertyPath]);
} else {
return array();
}
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment