Skip to content

Instantly share code, notes, and snippets.

@gonzalo123
Created April 9, 2012 13:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gonzalo123/2343390 to your computer and use it in GitHub Desktop.
Save gonzalo123/2343390 to your computer and use it in GitHub Desktop.
DocInject trait
<?php
trait DocInject
{
public function parseDocInject()
{
$reflection = new ReflectionClass($this);
foreach ($reflection->getProperties() as $property) {
$this->processProperty($property);
}
}
private function processProperty(ReflectionProperty $property)
{
$docComment = $this->cleanPhpDoc($property->getDocComment());
foreach (explode("\n", $docComment) as $item) {
if ($this->existsInjectDecorator($item)) {
$this->performDependencyInjection($property, $item);
}
}
}
private function cleanPhpDoc($docComment)
{
$docComment = preg_replace('#[ \t]*(?:\/\*\*|\*\/|\*)?[ ]{0,1}(.*)?#', '$1', $docComment);
$docComment = trim(str_replace('*/', null, $docComment));
return $docComment;
}
private function existsInjectDecorator($item)
{
return strpos($item, '@inject') !== false;
}
private function performDependencyInjection(ReflectionProperty $property, $item)
{
$injectString = $this->removeDecoratorFromPhpDoc($item);
$value = $this->compileInjectString($injectString);
$this->injectValueIntoProperty($property, $value);
}
private function removeDecoratorFromPhpDoc($item)
{
return trim(str_replace('@inject', null, $item));
}
private function compileInjectString($injectString)
{
$value = null;
eval("\$value = {$injectString};"); // yes, eval. uggly, isnt't?
return $value;
}
private function injectValueIntoProperty(ReflectionProperty $property, $value)
{
$property->setAccessible(true);
$property->setValue($this, $value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment