Retrieving all controller actions in an application

Site has moved

This site has moved to a new location. Visit the new site at http://programsdream.nl.

By Ronald van Belzen | May 3, 2013

Well not all actions, the method does not incorporate the CController actions() function to retrieve the external action classes of a controller, but these can be added quite easy for each controller found.

The method does not bother to search for nested modules either, but when you have them in your application you can add a search for them to the method.

/**
 * Find actions of all controllers, including controllers of unnested modules
 */ 
private function findControllerActions() {
  $actions = array(); 
  // import classes 
  Yii::import('application.controllers.*'); 
  foreach(Yii::app()->modules as $module => $array) { 
    Yii::import('application.modules.' . $module . '.controllers.*');
  } 
  // find root controller actions: 
  $appControllerPath = Yii::getPathOfAlias('application.controllers'); 
  if(is_dir($appControllerPath)) { 
    $fileLists = CFileHelper::findFiles($appControllerPath); 
  } else { 
    $fileLists = array(); 
  }
  foreach($fileLists as $controllerPath) { 
    $controllerName = substr($controllerPath, strrpos($controllerPath, DIRECTORY_SEPARATOR)+1,-4); 
    $methods = get_class_methods($controllerName); 
    foreach($methods as $method) { 
      if(strpos($method, 'action') !== false && $method != 'actions') { 
        $moduleId = null; 
        $controllerId = strtolower(substr($controllerName, 0, -10)); 
        $actionId = strtolower(substr($method, 6)); 
        $actions[] = array('module'=>$moduleId, 'controller'=>$controllerId, 'action'=>$actionId); 
      } 
    } 
  } 
  // find module controller actions: 
  foreach(Yii::app()->modules as $module => $array) { 
    $appControllerPath = Yii::getPathOfAlias('application.modules.' . $module . '.controllers');
    if(is_dir($appControllerPath)) { 
      $fileLists = CFileHelper::findFiles($appControllerPath);
    } else { 
      $fileLists = array(); 
    } 
    foreach($fileLists as $controllerPath) { 
      $controllerName = substr($controllerPath, strrpos($controllerPath, DIRECTORY_SEPARATOR)+1,-4);
      $methods = get_class_methods($controllerName); 
      foreach($methods as $method) {
        if(strpos($method, 'action') !== false && $method != 'actions') { 
          $moduleId = $module; 
          $controllerId = strtolower(substr($controllerName, 0, -10)); 
          $actionId = strtolower(substr($method, 6)); 
          $actions[] = array(
            'module'=>$moduleId, 
            'controller'=>$controllerId, 
            'action'=>$actionId
          ); 
        } 
      } 
    } 
  } 
  return $actions; 
}