我有很多PHP文件,我想检查源代码中使用的所有类是否都存在。例如,我们假设我们有以下代码:
use MyProject\Logger;
use MyProject\Libraires\Form;
class MyClass
{
public function startup()
{
Logger::addTrace("()"); << check that class '\MyProject\Logger' class exists
parent::startup();
$this->requirePermittedIp();
$form = new Form(); // << check that class \MyProject\Libraries\Form exists
$utils = new Utils(); // << check that \Utils class exists
Logger::addTrace("(-)");
}
}
我知道我可以使用token_get_all()
功能。我实际上尝试过,但我认为有人当然解决了这类问题。
答案 0 :(得分:0)
正则表达怎么样?我的例子,它适用于宣布新类。
function checkClassExists($string) {
if (!is_string($string)) {
return 'string required';
}
preg_match_all('/new\s+[A-Za-z\\\]+\((.)*\);/', $string, $classes);
foreach ($classes[0] as $key => $class) {
$classPrototype = str_replace('new', '', strstr($class, '(', true));
$className = trim(str_replace(';', '', $classPrototype));
echo (class_exists($className, true)) ? 'class ' . $className . ' exists <br/>' : 'class ' . $className . ' not exists <br/>';
}
}
include_once 'framework/classes/ClassLoader.php'; // before usage function need some calss loader
$autloader = new Classes\ClassLoader;
spl_autoload_register(array($autloader, 'handle'));
$stringTest = '<php? new \framework\classes\Application();
$a = new \framework\classes\ClassLoader($a,$b);
if($a instanceof \framework\classes\ClassLoader){
echo "helloworld";
}else{
$test = new \framework\classes\Application(array());
$result = $test->some();
foreach($result as $key => $value){
echo $key;
}
}new \framework\classes\Application($exception);
?>';
checkClassExists($stringTest);
输出:
class \framework\classes\Application exists
class \framework\classes\ClassLoader exists
class \framework\classes\Application exists
class \framework\classes\Application exists
函数在命名空间类上进行了测试,你需要开发函数来匹配静态方法和&#34; ::&#34;
答案 1 :(得分:0)
我使用了https://github.com/nikic/PHP-Parser。而且,它很容易使用。