Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active October 16, 2015 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzkmx/9f7392b28011efb712bb to your computer and use it in GitHub Desktop.
Save tzkmx/9f7392b28011efb712bb to your computer and use it in GitHub Desktop.
Abstract Class enabling examination of private properties and @var annotations.
<?php
class AbstractClassReflectable
{
/**
* @var \ReflectionClass
*/
private $_reflector;
private $_reflectedProperties;
public function getProperties()
{
return array_map(function ($p) {
return $p->getName();
}, $this->cacheProperties());
}
public function getTypes()
{
return array_reduce($this->cacheProperties(), function($rtArr, $p) {
$rtArr[] = $this->getVarTypeCommentLine($p->getDocComment());
return $rtArr;
});
}
private function cacheProperties()
{
$reflector = $this->getReflector();
if (!is_array($this->_reflectedProperties)) {
$this->_reflectedProperties = array_filter(
$reflector->getProperties(),
function($property) {
$name = $property->getName();
return (strpos($name, '_') === false);
});
}
return $this->_reflectedProperties;
}
private function getReflector()
{
if (get_class($this->_reflector) !== 'ReflectionClass') {
$this->_reflector = new \ReflectionClass($this);
}
return $this->_reflector;
}
private function getVarTypeCommentLine($docblock)
{
$block = preg_split("/\n/", $docblock);
$typeDeclarationLine = array_shift(array_filter($block, function($line) {
return !!strpos($line, '@var');
}));
preg_match("/^([^@]*)(@var )(.*)$/", $typeDeclarationLine, $matches);
return trim($matches[3]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment