Last active
December 29, 2015 09:49
-
-
Save b-b3rn4rd/7652855 to your computer and use it in GitHub Desktop.
Accessing array properties through magic getters and setters.
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 My; | |
use Doctrine\Common\Util\Inflector; | |
/** | |
* Allow to access array properties using getters/setters | |
* | |
* @method null set${Property}(mixed $value) set array property | |
* @method mixed get${Property}() get array property | |
* @author Bernard Baltrusaitis <[email protected]> | |
*/ | |
class ArrayObject extends \ArrayObject | |
{ | |
function __construct($array) | |
{ | |
parent::__construct($array, ArrayObject::ARRAY_AS_PROPS); | |
} | |
/** | |
* Magic method catches getters and setters | |
* | |
* @param string $name property name | |
* @param array $arguments property value | |
* @return mixed the value at the specified index or NULL. | |
* @throws \InvalidArgumentException | |
* @throws \BadMethodCallException | |
*/ | |
public function __call($name, $arguments) | |
{ | |
$matches = null; | |
if (preg_match('/^get(\w+)/', $name, $matches)) { | |
$property = Inflector::tableize($matches[1]); | |
if (0 !== sizeof($arguments)) { | |
throw new \InvalidArgumentException( | |
sprintf('The method `%s` does not expect arguments, %d given', | |
$name, sizeof($arguments))); | |
} | |
return $this->offsetGet($property); | |
} | |
if (preg_match('/^set(\w+)/', $name, $matches)) { | |
$property = Inflector::tableize($matches[1]); | |
if (1 !== sizeof($arguments)) { | |
throw new \InvalidArgumentException( | |
sprintf('The method `%s` expects exactly 1 argument, %d given', | |
$name, sizeof($arguments))); | |
} | |
return $this->offsetSet($property, current($arguments)); | |
} | |
throw new \BadMethodCallException( | |
sprintf('Class `%s` does not have `%s` method', __CLASS__, $name)); | |
} | |
/** | |
* Get the string representation of the current array | |
* | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return json_encode($this->getArrayCopy()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment