Skip to content

Instantly share code, notes, and snippets.

@auipga
Forked from beregond/gist:4373142
Last active July 30, 2019 15:04
Show Gist options
  • Save auipga/8142803018129856375c9e26eb3715b9 to your computer and use it in GitHub Desktop.
Save auipga/8142803018129856375c9e26eb3715b9 to your computer and use it in GitHub Desktop.
Allows to abandon necessity to define all setters and getters in Doctrine's entities (works perfectly with Symfony + Doctrine + Twig).
<?php
namespace Vendor\TestBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* General class for all entities.
*/
abstract class Entity
{
/**
* Magic getter and setter for entity.
*
* @throws \Exception
* @param string $method
* @param array $arguments
* @return mixed
*/
public function __call($method, $arguments)
{
/* @see \Doctrine\ORM\Mapping\UnderscoreNamingStrategy::underscore() */
$prop = strtolower(preg_replace(['/^[sg]et/', '/(?<=[a-z])([A-Z])/'], ['', '_$1'], $method));
if (preg_match('/^set/', $method)) {
if ($this->$prop instanceof ArrayCollection) {
throw new \Exception('You can\'t overwrite "'.$prop.'" property.');
}
$this->$prop = array_shift($arguments);
return $this;
} elseif (preg_match('/^get/', $method)) {
if (!property_exists(get_class($this), $prop)) {
throw new \Exception(sprintf('There\'s no property named "%s"', $prop));
}
return $this->$prop;
} else {
$vars = array_keys(get_object_vars($this));
if (in_array($method, $vars)) {
return call_user_func_array(array($this, 'get' . ucfirst($method)), $arguments);
}
throw new \Exception('Method "'.$method.'" is not defined.');
}
}
/**
* Triggered while accessing entity property.
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
return call_user_func(array($this, 'get' . ucfirst($name)));
}
/**
* Triggered while setting entity property.
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
{
return call_user_func(array($this, 'set' . ucfirst($name)), $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment