Hello everybody,
I'm writing a Symfony2 command to generate classes and retain code from existent files that it tagged with a certain annotation. I'm using Reflection to inspect the existent classes.
So far, I've managed to retain methods, but properties are giving me issues.
This is my code:
protected function retainCode($from, $to)
{
$class = new \ReflectionClass($from);
$file = $class->getFileName();
$stream=fopen($to, 'w');
//Check properties
foreach ($class->getProperties() as $property)
{
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$annotation = $reader->getPropertyAnnotations($property, 'RetainCode');
if ($annotation != null)
{
$contents = file($file);
$start_line = $property->getStartLine() - 1;
$prefix=$property->getDocComment();
$code = PHP_EOL.' '.$prefix.PHP_EOL.implode("", array_slice($contents, $start_line, ($property->getEndLine()-$start_line)));
fwrite($stream, $code);
}
}
//Check methods
foreach ($class->getMethods() as $method)
{
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$annotation = $reader->getMethodAnnotations($method, 'RetainCode');
if ($annotation != null)
{
$contents = file($file);
$start_line = $method->getStartLine() - 1;
$prefix=$method->getDocComment();
$code = PHP_EOL.' '.$prefix.PHP_EOL.implode("", array_slice($contents, $start_line, ($method->getEndLine()-$start_line)));
fwrite($stream, $code);
}
}
fclose($stream);
}
The implementation for methods works, but \ReflectionProperty does not contain any methods to get the position of the defined property. (Seems to me it should actually have such option)
Is there any way to get this, in a proper way?
Thanks in advance!