Created
February 15, 2013 12:17
-
-
Save gooh/4960073 to your computer and use it in GitHub Desktop.
Just a proof of concept for an attribute reader trait
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 | |
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
wtf is this comment section? R u tryin to hack github or wot ? Lol.