Created
November 11, 2013 21:53
-
-
Save spolischook/7421120 to your computer and use it in GitHub Desktop.
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
<?php | |
namespace YourVendor\YourBundle; | |
use Doctrine\Common\Collections\ArrayCollection; | |
use Doctrine\Common\Collections\Collection; | |
class DynamicCollection extends ArrayCollection | |
{ | |
public function __call($method, $arguments) | |
{ | |
$property = substr($method, 3, strlen($method)); | |
$property = lcfirst($property); | |
if ('get' == substr($method, 0, 3)) { | |
if (!$this->containsKey($property)) { | |
throw new \BadMethodCallException( | |
"Undefined property '$property'. Did you set it first?" | |
); | |
} | |
return $this->get($property); | |
} elseif ('set' == substr($method, 0, 3)) { | |
$this->set($property, $arguments[0]); | |
return $this; | |
} elseif ('add' == substr($method, 0, 3)) { | |
if (!$this->containsKey($property)) { | |
$this->set($property, new ArrayCollection()); | |
} | |
$this->get($property)->add($arguments[0]); | |
return $this; | |
} else { | |
throw new \BadMethodCallException( | |
"Undefined method '$method'. The method name must start with " . | |
"either add, set or get!" | |
); | |
} | |
} | |
public function toArrayRecursive() | |
{ | |
$resultedArray = array(); | |
foreach ($this->toArray() as $key => $element) { | |
if (is_object($element) && 'Exercise\ProgramBundle\Model\DynamicCollection' == get_class($element)) { | |
$resultedArray[$key] = $element->toArrayRecursive(); | |
} elseif (is_object($element) && in_array('Doctrine\Common\Collections\Collection', class_implements($element))) { | |
$resultedArray[$key] = $element->toArray(); | |
} else { | |
$resultedArray[$key] = $element; | |
} | |
} | |
return $resultedArray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment