Exakat\Phpexec::getTokenFromFile PHP Méthode

getTokenFromFile() public méthode

public getTokenFromFile ( $file )
    public function getTokenFromFile($file)
    {
        $file = str_replace('$', '\\\\$', $file);
        if ($this->isCurrentVersion) {
            $tokens = @token_get_all(file_get_contents($file));
        } else {
            $tmpFile = tempnam(sys_get_temp_dir(), 'Phpexec');
            shell_exec($this->phpexec . '  -d short_open_tag=1  -r "print \'<?php \\$tokens = \'; var_export(@token_get_all(file_get_contents(\'' . $file . '\'))); print \'; ?>\';" > ' . $tmpFile);
            include $tmpFile;
            unlink($tmpFile);
        }
        // In case the inclusion failed at parsing time
        if (!isset($tokens)) {
            $tokens = array();
        }
        return $tokens;
    }

Usage Example

Exemple #1
0
 private function countLocInFile($filename)
 {
     $return = array('comments' => 0, 'whitespace' => 0, 'tokens' => 0, 'total' => 0, 'code' => 0, 'files' => 1);
     $lines = array();
     $php = new Phpexec();
     $tokens = $php->getTokenFromFile($filename);
     if (empty($tokens)) {
         display("{$filename} is empty\n");
         $return['files'] = 0;
         $return['error'] = self::EMPTYFILE;
         return $return;
     }
     // One token if it fails compilation but we don't know the error
     if (count($tokens) == 1) {
         display("{$filename} doesn't compile\n");
         $return['files'] = 0;
         $return['error'] = self::INCOMPILABLE;
         return $return;
     }
     $line = 0;
     foreach ($tokens as $token) {
         if (is_array($token)) {
             $line = $token[2];
             $tokenName = token_name($token[0]);
             // counting comments
             if ($tokenName == 'T_DOC_COMMENT') {
                 $return['comments'] += substr_count($token[1], "\n") + 1;
             } elseif ($tokenName == 'T_COMMENT') {
                 ++$return['comments'];
             } elseif ($tokenName == 'T_WHITESPACE') {
                 ++$return['whitespace'];
             } else {
                 if (isset($lines[$line])) {
                     ++$lines[$line];
                 } else {
                     $lines[$line] = 1;
                 }
                 ++$return['tokens'];
             }
         } else {
             ++$return['tokens'];
             if (!in_array($token, array('{', '}'))) {
                 if (isset($lines[$line])) {
                     ++$lines[$line];
                 } else {
                     $lines[$line] = 1;
                 }
             }
         }
     }
     if (is_array($token) && $tokenName == 'T_CLOSE_TAG') {
         --$lines[$line];
         if ($lines[$line] == 0) {
             unset($lines[$line]);
             --$line;
         }
     }
     $return['total'] = $line;
     $return['code'] = count($lines);
     $return['error'] = self::OK;
     return $return;
 }