Markdown.php
2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
namespace Lackoxygen\ShowDocGeneration\Writer;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use Lackoxygen\ShowDocGeneration\Annotations\Method;
use Lackoxygen\ShowDocGeneration\Parser\Doc;
class Markdown
{
protected string $template = <<<t
##### 简要描述
- {{title}}
##### 请求URL
- ` {{url}} `
##### 请求方式
- {{method}}
##### 参数
|参数名|必选|类型|说明|
|:----|:---|:----- |-----|
{{params}}
##### 中间件
{{middles}}
##### 请求头
|参数名|说明|
|:---- |:---|
{{headers}}
##### 返回示例
```
{{resp}}
```
##### 返回参数说明
|参数名|类型|说明|
|:-----|:-----|:-----------------------------|
{{respRemark}}
##### 备注
- 最后更新时间:{{updateTime}}
t;
protected string $output = '';
public function __construct(Doc $doc, string $resourcePath)
{
$editTemplate = $this->template;
$replaces = [
'title' => Arr::get($doc->title, 'value'),
'url' => Arr::get($doc->url, 'path'),
'method' => Arr::get($doc->method, 'method', Method::METHOD_GET),
'headers' => join("\n", $this->tableTbody($doc->headerLine)),
'params' => join("\n", $this->tableTbody($doc->paramLine)),
'resp' => '{}',
'respRemark' => join("\n", $this->tableTbody($doc->respLine)),
'middles' => join("\n", $this->unorderedList($doc->middles)),
'updateTime' => now()->toString()
];
$respResource = Arr::get($doc->respResource, 'resource');
if ($respResource) {
$resourceInfo = pathinfo($respResource);
if (!isset($resourceInfo['extension'])) {
$respResource .= '.json';
}
$resourceFile = rtrim($resourcePath, '/\\') . DIRECTORY_SEPARATOR . $respResource;
$fs = new Filesystem();
if ($fs->exists($resourceFile) && $respData = $fs->sharedGet($resourceFile)) {
Arr::set($replaces, 'resp', $respData);
}
}
$this->output = \str_replace(
\array_map(function (string $key) {
return '{{' . $key . '}}';
}, \array_keys($replaces)),
\array_values($replaces),
$editTemplate
);
}
protected function unorderedList(array $list): array
{
return \array_map(function ($v) {
return '- ' . $v;
}, $list);
}
protected function tableTbody(array $tbody): array
{
return \array_map(function (array $line) {
$line = \array_map(function ($v) {
if (\is_bool($v)) {
$v = $v ? '是' : '否';
}
return $v;
}, $line);
return '|' . \join('|', \array_values($line)) . '|';
}, $tbody);
}
public function toString(): string
{
return $this->output;
}
}