123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- <?php
- namespace app\doc;
- class Parser
- {
- /**
- * 解析类
- * @param $object
- *
- * @return array
- */
- public function parse_class($object)
- {
- $list = $this->parseCommentArray($this->comment2Array($object));
- return $list;
- }
- /**
- * @param \ReflectionClass $object
- *
- * @return array|bool
- */
- public function parse_action($object)
- {
- $comment = $this->parseCommentArray($this->comment2Array($object));
- if (!isset($comment['url']) || !$comment['url']) {
- $comment['url'] = $this->buildUrl($object);
- }
- if (!isset($comment['method']) || !$comment['method']) {
- $comment['method'] = 'GET';
- }
- $comment['href'] = "{$object->class}::{$object->name}";
- return $comment;
- }
- /**
- * @title 生成请求地址
- * @param \ReflectionClass $object
- * @return mixed
- */
- private function buildUrl($object)
- {
- $_arr = explode('\\', $object->class);
- array_shift($_arr);
- $a = array_shift($_arr);
- array_shift($_arr);
- $url = $a.DS.implode('.',$_arr).DS.$object->name;
- $url = \think\facade\Route::buildUrl($url)->domain(true)->suffix(false)->build();
- return $url;
- }
- /**
- * 注释字符串转数组
- *
- * @param string $comment
- *
- * @return array
- */
- private function comment2Array($comment = '')
- {
- // 多空格转换成单空格
- $comment = str_replace(':', ' ', $comment);
- $comment = preg_replace('/[ ]+/', ' ', $comment);
- preg_match_all('/[\*+][\s+]?@(.*?)[\n|\r]/is', $comment, $matches);
- $arr = [];
-
- foreach ($matches[1] as $key => $match) {
- $arr[$key] = explode(' ', $match);
- }
- return $arr;
- }
- /**
- * 解析注释数组
- *
- * @param array $array
- *
- * @return array
- */
- private function parseCommentArray(array $array = [])
- {
- $newArr = [];
- foreach ($array as $item) {
- $item[0] = trim(strtolower($item[0]),":");
- switch (trim(strtolower($item[0]),":")) {
- case 'title':
- case 'desc':
- case 'version':
- case 'author':
- default:
- $newArr[$item[0]] = isset($item[1]) ? $item[1] : '-';
- break;
- case 'url':
- @eval('$newArr["url"]=(' . $item[1] . ');');
- break;
- case 'icon':
- //默认使用font-awesome图标
- $first = isset($item[1])&&isset($item[2])?$item[1]:"fa";
- $second = isset($item[2])?$item[2]:(isset($item[1])?$item[1]:"fa-leaf");
- $newArr[$item[0]] = $first." ".$second;
- break;
- case 'param':
- case 'return':
- $newArr[$item[0]][] = [
- 'type' => trim($item[1],"\{\\\}"),
- 'name' => isset($item[2])?trim($item[2],"\{\\\}"):'',
- 'default' => isset($item[3]) ? trim($item[3],"\{\\\}") : '-',
- 'desc' => isset($item[4]) ? trim($item[4],"\{\\\}") : '-'
- ];
- break;
- }
- }
- if(empty($newArr['icon'])){
- $newArr['icon'] = "fa fa-leaf";
- }
- return $newArr;
- }
- }
|