Created
February 22, 2012 16:27
-
-
Save naholyr/1885879 to your computer and use it in GitHub Desktop.
Extract namespace from a PHP file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this matching method to prevent false positives
example of false positive is