Created
February 20, 2016 10:43
-
-
Save abhinavkumar940/21438e48be5060058bd2 to your computer and use it in GitHub Desktop.
Form
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 ApiBundle\Service; | |
use Symfony\Component\Form\FormInterface; | |
/** | |
* Description of FormErrorSerializer | |
* | |
* @author Abhinav Kumar <[email protected]> | |
* | |
*/ | |
class FormErrorsSerializer | |
{ | |
public function serializeFormErrors(FormInterface $form, $flat_array = false, $add_form_name = false, $glue_keys = '_') | |
{ | |
$errors = array(); | |
$errors['global'] = array(); | |
$errors['fields'] = array(); | |
foreach ($form->getErrors() as $error) { | |
$errors['global'][] = $error->getMessage(); | |
} | |
$errors['fields'] = $this->serialize($form); | |
if ($flat_array) { | |
$errors['fields'] = $this->arrayFlatten($errors['fields'], | |
$glue_keys, (($add_form_name) ? $form->getName() : '')); | |
} | |
return $errors; | |
} | |
private function serialize(FormInterface $form) | |
{ | |
$local_errors = array(); | |
foreach ($form->getIterator() as $key => $child) { | |
foreach ($child->getErrors() as $error){ | |
$local_errors[$key] = $error->getMessage(); | |
} | |
if (count($child->getIterator()) > 0) { | |
$local_errors[$key] = $this->serialize($child); | |
} | |
} | |
return $local_errors; | |
} | |
private function arrayFlatten($array, $separator = "_", $flattened_key = '') { | |
$flattenedArray = array(); | |
foreach ($array as $key => $value) { | |
if(is_array($value)) { | |
$flattenedArray = array_merge($flattenedArray, | |
$this->arrayFlatten($value, $separator, | |
(strlen($flattened_key) > 0 ? $flattened_key . $separator : "") . $key) | |
); | |
} else { | |
$flattenedArray[(strlen($flattened_key) > 0 ? $flattened_key . $separator : "") . $key] = $value; | |
} | |
} | |
return $flattenedArray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment