public
Created

DocInject trait

  • Download Gist
DocInject.trait.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
<?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);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.