Skip to content

Instantly share code, notes, and snippets.

@naholyr
Created February 22, 2012 16:27
Show Gist options
  • Save naholyr/1885879 to your computer and use it in GitHub Desktop.
Save naholyr/1885879 to your computer and use it in GitHub Desktop.
Extract namespace from a PHP file
<?php
// Works in every situations
function by_token ($src) {
$tokens = token_get_all($src);
$count = count($tokens);
$i = 0;
$namespace = '';
$namespace_ok = false;
while ($i < $count) {
$token = $tokens[$i];
if (is_array($token) && $token[0] === T_NAMESPACE) {
// Found namespace declaration
while (++$i < $count) {
if ($tokens[$i] === ';') {
$namespace_ok = true;
$namespace = trim($namespace);
break;
}
$namespace .= is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i];
}
break;
}
$i++;
}
if (!$namespace_ok) {
return null;
} else {
return $namespace;
}
}
// Makes many assumptions on file format:
// namespace is declared on its own line, starting with "namespace" (no spaces).
function by_regexp($src) {
if (preg_match('#^namespace\s+(.+?);$#sm', $src, $m)) {
return $m[1];
}
return null;
}
function bench($foo, $src) {
$start = microtime(true);
for ($i=0; $i<10000; $i++) {
$ns = $foo($src);
if ($ns !== 'Acme\\HelloBundle\\DependencyInjection') {
throw new Exception('Mother fucker ?');
}
}
$end = microtime(true);
return $end - $start;
}
$src = file_get_contents("/path/to/file.php");
var_dump(bench('by_token', $src), bench('by_regexp', $src));
// Result on my machine for "Acme\HelloBundle\DependencyInjection":
// float(1.6613008975983)
// float(0.1151180267334)
@Mahmoudz
Copy link

Mahmoudz commented Oct 6, 2016

Thankss

@tschallacka
Copy link

I use this matching method to prevent false positives

    if (preg_match('#(namespace)(\\s+)([A-Za-z0-9\\\\]+?)(\\s*);#sm', $line, $m)) {
        return $m[3];
    }
    return null;

example of false positive is

  echo "The namespace is defined as a Foo\Bar\Baz";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment