You are here

protected function RegistryAutoloadSearcher::parseFile in Registry Autoload 7

Parses a file for classes and interfaces, including the namespace.

This lifts the core limitation of not supporting namespaces.

This code is now based on \Symfony\Component\ClassLoader\ClassMapGenerator::findClasses()

Parameters

object $entry: The registry entry as defined in processFiles(). The classes key will be updated in the entry if classes can be found.

string $filename: The filename to parse.

Return value

bool TRUE if classes could be found, FALSE otherwise.

See also

_registry_parse_file()

1 call to RegistryAutoloadSearcher::parseFile()
RegistryAutoloadSearcher::processFiles in ./registry_autoload.module
Processes files containing classes for the given module.

File

./registry_autoload.module, line 292
Main module for enabling core registry to support namespaced files.

Class

RegistryAutoloadSearcher
RegistryAutoloadSearcher helper class.

Code

protected function parseFile($entry, $filename) {
  $contents = file_get_contents($filename);
  $namespace = '';

  // Check if this version of PHP supports traits.
  $traits = version_compare(PHP_VERSION, '5.4', '<') ? '' : '|trait';

  // Return early if there is no chance of matching anything in this file.
  if (!preg_match('{\\b(?:class|interface' . $traits . ')\\s}i', $contents)) {
    return array();
  }
  $tokens = token_get_all($contents);
  for ($i = 0, $max = count($tokens); $i < $max; $i++) {
    $token = $tokens[$i];
    if (is_string($token)) {
      continue;
    }
    $class = '';
    $token_name = token_name($token[0]);
    switch ($token_name) {
      case "T_NAMESPACE":
        $namespace = '';

        // If there is a namespace, extract it
        while (($t = $tokens[++$i]) && is_array($t)) {
          if (in_array($t[0], array(
            T_STRING,
            T_NS_SEPARATOR,
          ))) {
            $namespace .= $t[1];
          }
        }
        $namespace .= '\\';
        break;
      case "T_CLASS":
      case "T_INTERFACE":
      case "T_TRAIT":

        // Find the classname
        while (($t = $tokens[++$i]) && is_array($t)) {
          if (T_STRING === $t[0]) {
            $class .= $t[1];
          }
          elseif ($class !== '' && T_WHITESPACE == $t[0]) {
            break;
          }
        }
        $class_name = ltrim($namespace . $class, '\\');
        $type = 'class';
        if ($token[0] == T_INTERFACE) {
          $type = 'interface';
        }
        $entry->classes[$class_name] = array(
          'name' => $class_name,
          'type' => $type,
        );
        break;
      default:
        break;
    }
  }
  return TRUE;
}