Skip to content

Instantly share code, notes, and snippets.

@gooh
Created February 15, 2013 12:17
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gooh/4960073 to your computer and use it in GitHub Desktop.
Just a proof of concept for an attribute reader trait
<?php
trait AttributeReader
{
/**
* Interceptor for non-accessible properties
*
* @param string $property
* @returns mixed
*/
public function __get($property)
{
return $this->readAttribute($property);
}
/**
* Attribute Reader
*
* Checks whether the requested non-accessible property exists
* in {@link readableAttributes()}. When a Getter get<Property>
* exists for this property, the Getter is invoked and it's
* return value is returned. If no Getter exists but a property
* of that name then the raw value of that property is returned.
*
* @throws DomainException When Property is not in list of readable attributes
* @throws DomainException When neither Getter nor Property exists
* @param string $property
* @return mixed
*/
private function readAttribute($property)
{
$this->assertPropertyIsMarkedReadable($property);
if (method_exists($this, "get$property")) {
return call_user_func(array($this, "get$property"));
}
$this->assertPropertyExists($property);
return $this->$property;
}
/**
* @throws DomainException When Property is not in list of readable attributes
* @param string $property
* @return void
*/
private function assertPropertyIsMarkedAccessible($property)
{
if (false === in_array($property, $this->readableAttributes())) {
throw new \DomainException(
"Property $property is not in list of readable attributes"
);
}
}
/**
* @throws DomainException When Property does not exist
* @param string $property
* @return void
*/
private function assertPropertyExists($property)
{
if (false === property_exists($this, $property)) {
throw new \DomainException("Property $property does not exist");
}
}
/**
* Returns the list of readable attributes
*
* @return array
*/
abstract protected function readableAttributes();
}
@noc2spam
Copy link

wtf is this comment section? R u tryin to hack github or wot ? Lol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment