0

How to get the code of the method? I'm trying something like this: :

//SiteController.php
class SiteController{

  public function actionIndex(){
      //bla bla..
  }

  public function actionCustomMethod(){
      if(1){
          echo '1';
      } else {
          echo '2';
      }
  }

}

//i need take code of "function actionCustomMethod(){ ... }"

preg_match('/function actionCustomMethod[^}]+/i', file_get_contents('SiteController.php'), $out);

//but the preg_match returns
/*
public function actionCustomMethod(){
    if(1){
      echo '1';
*/

I don't know how to get the code with nested braces. Any ideas?

1 Answers1

0
class SiteController{

  public function actionIndex(){
      //bla bla..
  }

  public function actionCustomMethod(){
      if(1){
         echo '1';
      } else {
          echo '2';
      }
  }

}
$res = new ReflectionMethod('SiteController', 'actionCustomMethod');
    $start = $res->getStartLine();
$end = $res->getEndLine();
$file = $res->getFileName();

echo 'get from '.$start.' to '.$end .' from file '.$file.'<br/>';
$lines = file($file);
$fct = '';
for($i=$start;$i<$end+1;$i++)
{
    $num_line = $i-1; // as 1st line is 0
    $fct .= $lines[$num_line];
}
echo '<pre>';
echo $fct;
Asenar
  • 6,732
  • 3
  • 36
  • 49
  • Well, it works. But how to use ReflectionMethod for the string data? Like this: file_get_contents('SiteController.php') ? – user2629587 Oct 29 '13 at 17:53
  • If your question is about class and properties, you can look at ReflectionClass documentation and process similar way for property (`$reflectionClass->getProperties()` and similar ) – Asenar Oct 29 '13 at 23:52
  • I solved the problem like that. preg_match_all('/function[^\{]+\{(.*)\}/Ux', file_get_contents('SiteController.php'), $matches); – user2629587 Oct 30 '13 at 09:30
  • or preg_match_all('/function[^\{]+\{(.*)\}/Uxs', file_get_contents('SiteController.php'), $matches); – user2629587 Oct 30 '13 at 10:35
  • If you want to do this for checking code for security, you cannot trust that regex : If the php file you want to check is sent by a user, he can send whatever he wants (including functions inside methods, or using tricky `{`/`}` ) – Asenar Oct 30 '13 at 10:35
  • I will use it to analyze and spot-on controllers/action in the "backend", with ajax. I'm trying to create a user interface for MVC structures. – user2629587 Oct 30 '13 at 10:48