Skip to content

Instantly share code, notes, and snippets.

@spolischook
Created November 11, 2013 21:53
Show Gist options
  • Save spolischook/7421120 to your computer and use it in GitHub Desktop.
Save spolischook/7421120 to your computer and use it in GitHub Desktop.
<?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