从Symfony 2中的自定义命令读取控制器自定义注释

时间:2015-05-25 11:04:13

标签: php symfony annotations

我已创建自定义注释以生成JSON文件(如果您要求,则为NodeRed ...),并且我在虚拟控制器中通过虚拟方法成功测试它们。

我想将所有内容移植到自定义Sf命令,其作用是读取我的bundle中的所有Controllers注释并获得相同的结果(也就是创建JSON文件)。

我怎么能实现这一目标?使用finder循环遍历XxxxController.php文件是一个不错的选择吗? 还是太野心勃勃了? :P

注释示例:

/**
 * @NodeRedFlows(
 *     triggerBy="testFlow", options={"interval":"45"}  
 * )
 */
 public function indexAction() { /*...*/ }

很抱歉,发布更多代码并不容易,因为我有整个读者类,注释类和另一个基于triggerBy="testFlow" id创建JSON流的类。

底线:*

我希望能够从Command中创建我的JSON流文件,而不是在我的Controller中创建我的JSON流文件(用于测试)。

1 个答案:

答案 0 :(得分:2)

加载已在Symfony中分配了路径的所有控制器操作(请参阅thisthis)。

然后为每个找到的控制器操作加载注释:

use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\HttpFoundation\Request;

$annotationReader = new AnnotationReader();
$routes = $this->container->get('router')->getRouteCollection()->all();
$this->container->set('request', new Request(), 'request');

foreach ($routes as $route => $param) {
    $defaults = $params->getDefaults();

    if (isset($defaults['_controller'])) {
         list($controllerService, $controllerMethod) = explode(':', $defaults['_controller']);
         $controllerObject = $this->container->get($controllerService);
         $reflectedMethod = new \ReflectionMethod($controllerObject, $controllerMethod);

         // the annotations
         $annotations = $annotationReader->getMethodAnnotations($reflectedMethod );
    }
}

<强>更新

如果您需要所有控制器方法,包括那些没有@Route注释的方法,那么我会按照您在问题中的建议进行操作:

// Load all registered bundles
$bundles = $this->container->getParameter('kernel.bundles');

foreach ($bundles as $name => $class) {
    // Check these are really your bundles, not the vendor bundles
    $bundlePrefix = 'MyBundle';
    if (substr($name, 0, strlen($bundlePrefix)) != $bundlePrefix) continue;

    $namespaceParts = explode('\\', $class);
    // remove class name
    array_pop($namespaceParts);
    $bundleNamespace = implode('\\', $namespaceParts);
    $rootPath = $this->container->get('kernel')->getRootDir().'/../src/';
    $controllerDir = $rootPath.$bundleNamespace.'/Controller';

    $files = scandir($controllerDir);
    foreach ($files as $file) {
        list($filename, $ext) = explode('.', $file);
        if ($ext != 'php') continue;

        $class = $bundleNamespace.'\\Controller\\'.$filename;
        $reflectedClass = new \ReflectionClass($class);

        foreach ($reflectedClass->getMethods() as $reflectedMethod) {
            // the annotations
            $annotations = $annotationReader->getMethodAnnotations($reflectedMethod);
        }
    }
}
相关问题