Created
February 22, 2019 14:12
-
-
Save AndreiLN/3708ab829c26cee4711b1df551d1385f to your computer and use it in GitHub Desktop.
Converts Doctrine Model to Array
This file contains 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
/** | |
* Converts doctrine to array | |
* @param $data | |
* @param $single it's run's only once (no recursion) | |
* @return array | |
*/ | |
public function doctrine_to_array($data, $single = false) { | |
if (is_object($data)) { // its object | |
$methods = get_class_methods($data); | |
$methods = array_filter($methods, function($val){ return preg_match('/^get/', $val); }); | |
$return = []; | |
if(count($methods)){ | |
foreach($methods as $method){ | |
$prop = lcfirst(preg_replace('/^get/', "", $method)); | |
$val = $data->$method(); | |
if(!$single){ | |
$return[$prop] = $this->doctrine_to_array($val, $single); | |
} else { | |
if(!is_array($val) && !is_object($val)){ | |
$return[$prop] = $val; | |
} | |
} | |
} | |
} | |
return $return; | |
} else if(is_array($data)){ | |
if(count($data)){ | |
foreach($data as $idx => $val){ | |
$data[$idx] = $this->doctrine_to_array($val, $single); | |
} | |
} | |
} | |
return $data; // it's not array or object | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment