您的位置:首页 > 编程语言

利用反射类来获取代码中提供的接口

2018-03-05 00:00 375 查看
<?php
/**
* Created by PhpStorm.
* User: Zhoulang
* Date: 2018/1/12
* Describe: 利用反射类来获取本项目所有对应的非静态、非析构、非构造的方法(获取控制器访问节点)
*/

namespace app\common\traits;

use \ReflectionClass;
use \ReflectionMethod;

trait AuthNodes
{
/**
* @return array
*/
public function getModuleAuthNodes(){
$path = APP_PATH;
$fileList = scandir($path);
$ListArr = [];
//遍历模块
foreach($fileList as $key=>$value){
$nowPath = $path.$value;
if($value!=='.' && $value!=='..' && is_dir($nowPath)){
$nowPathLi = $nowPath.DIRECTORY_SEPARATOR.'controller';
$fileListLi = scandir($nowPathLi);
//遍历模块中的控制器
foreach($fileListLi as $k=>$v){
$liPath = $nowPathLi.DIRECTORY_SEPARATOR.$v;
if($value!=='.' && $value!=='..' && is_file($liPath)){
// &&
//文件后缀名
$extArr = explode('.',$v);
$ext = end($extArr);

if($ext!=='php')
continue;

$ListArr[$value][$extArr[0]] = [];
}
}
}
}

foreach($ListArr as $key=>$value){

$module = $key;

foreach($ListArr[$key] as $k=>$v){

$controller = $k;

$classNamespacePath = "app\\{$module}\\controller\\{$controller}";

$ListArr[$key][$k] = $this->getClassFunction($classNamespacePath);

}

}

return $ListArr;
}

protected function getClassFunction($classNamespacePath){
$reflection = new ReflectionClass($classNamespacePath);

$publicFuncs = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);

//ReflectionClass::getConstructor

$funcs = [];

foreach($publicFuncs as $key=>$value){

//不是构造方法  不是析构方法 也不是静态方法
if(!$value->isConstructor() && !$value->isDestructor() && !$value->isStatic()){

//获取方法注释信息
$funcDoc = $value->getDocComment();
//方法描叙
$describe = '';
//正则匹配出 /** info: xxxx  */ 格式的注释 中的 info:xxxxxxxx
if($funcDoc){
$preg_match = [];
$result = preg_match('/info[\s]?[\:|\:]{1}[\s]?([\S]*)/',$funcDoc,$preg_match);
if($result){
$describe = $preg_match[1];
}
}

$funcs[$value->name] = [
'info' => $describe
];
}
}
return $funcs;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反射类