Created
April 9, 2012 13:25
-
-
Save gonzalo123/2343390 to your computer and use it in GitHub Desktop.
DocInject 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 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