forked from Cherry-Pie/ApiDocs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApiDocs.php
333 lines (264 loc) · 10.4 KB
/
ApiDocs.php
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php
namespace Yaro\ApiDocs;
use ReflectionClass;
use Illuminate\Routing\Router;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Http\Request;
use Yaro\ApiDocs\Blueprint;
class ApiDocs
{
private $router;
private $config;
private $request;
public function __construct(Router $router, Config $config, Request $request)
{
$this->router = $router;
$this->config = $config;
$this->request = $request;
} // end __construct
public function show($routePrefix = null)
{
$currentPrefix = $this->request->get('prefix', $this->getRoutePrefix($routePrefix));
$endpoints = $this->getEndpoints($currentPrefix);
$endpoints = $this->getSortedEndpoints($endpoints);
$prefixes = $this->getRoutePrefixes();
$endpoints = $endpoints['App']['Http']['Controllers']['API'];
return view('apidocs::docs', compact('endpoints', 'prefixes', 'currentPrefix'));
} // end show
public function blueprint($routePrefix = null)
{
$routePrefix = $this->request->get('prefix', $this->getRoutePrefix($routePrefix));
$blueprint = app()->make(Blueprint::class);
$blueprint->setRoutePrefix($routePrefix);
$blueprint->setEndpoints($this->getEndpoints($routePrefix));
return $blueprint;
} // end blueprint
private function getEndpoints($routePrefix)
{
$endpoints = [];
foreach ($this->router->getRoutes() as $route) {
if (!$this->isPrefixedRoute($route, $routePrefix) || $this->isClosureRoute($route) || $this->isExcluded($route)) {
continue;
}
$actionController = explode("@", $this->getRouteParam($route, 'action.controller'));
$class = $actionController[0];
$method = $actionController[1];
if (!class_exists($class) || !method_exists($class, $method)) {
continue;
}
list($title, $description, $params) = $this->getRouteDocBlock($class, $method);
$key = $this->generateEndpointKey($class);
$endpoints[$key][] = [
'hash' => $this->generateHashForUrl($key, $route, $method),
'uri' => $this->getRouteParam($route, 'uri'),
'name' => $method,
'methods' => $this->getRouteParam($route, 'methods'),
'docs' => [
'title' => $title,
'description' => trim($description),
'params' => $params,
'uri_params' => $this->getUriParams($route),
],
];
}
return $endpoints;
} // end getEndpoints
private function isExcluded($route)
{
$uri = $this->getRouteParam($route, 'uri');
$actionController = $this->getRouteParam($route, 'action.controller');
return $this->isExcludedClass($actionController) || $this->isExcludedRoute($uri);
} // end isExcluded
private function isExcludedRoute($uri)
{
foreach ($this->config->get('yaro.apidocs.exclude.routes', []) as $pattern) {
if (str_is($pattern, $uri)) {
return true;
}
}
return false;
} // end isExcludedRoute
private function isExcludedClass($actionController)
{
foreach ($this->config->get('yaro.apidocs.exclude.classes', []) as $pattern) {
if (str_is($pattern, $actionController)) {
return true;
}
}
return false;
} // end isExcludedClass
private function isPrefixedRoute($route, $routePrefix)
{
$regexp = '~^'. preg_quote($routePrefix) .'~';
return preg_match($regexp, $this->getRouteParam($route, 'uri'));
} // end isPrefixedRoute
private function getRoutePrefix($routePrefix)
{
$prefixes = $this->getRoutePrefixes();
return in_array($routePrefix, $prefixes) ? $routePrefix : array_shift($prefixes);
}
private function getRoutePrefixes()
{
$prefixes = $this->config->get('yaro.apidocs.prefix', 'api');
if (!is_array($prefixes)) {
$prefixes = [$prefixes];
}
return $prefixes;
}
private function isClosureRoute($route)
{
$action = $this->getRouteParam($route, 'action.uses');
return is_object($action);
} // end isClosureRoute
private function getRouteDocBlock($class, $method)
{
$reflector = new ReflectionClass($class);
$title = implode(' ', $this->splitCamelCaseToWords($method));
$title = ucfirst(strtolower($title));
$description = '';
$params = [];
$docs = explode("\n", $reflector->getMethod($method)->getDocComment());
$docs = array_filter($docs);
if (!$docs) {
return [$title, $description, $params];
}
$docs = $this->filterDocBlock($docs);
$title = array_shift($docs);
$checkForLongDescription = true;
foreach ($docs as $line) {
if ($checkForLongDescription && !preg_match('~^@\w+~', $line)) {
$description .= trim($line) .' ';
} elseif (preg_match('~^@\w+~', $line)) {
$checkForLongDescription = false;
if (preg_match('~^@param~', $line)) {
$paramChunks = $this->getParamChunksFromLine($line);
$paramType = array_shift($paramChunks);
$paramName = substr(array_shift($paramChunks), 1);
$params[$paramName] = [
'type' => $paramType,
'name' => $paramName,
'description' => implode(' ', $paramChunks),
'template' => $this->getParamTemplateByType($paramType),
];
}
}
}
return [$title, $description, $params];
} // end getRouteDocBlock
private function getParamTemplateByType($paramType)
{
switch ($paramType) {
case 'file':
return 'file';
case 'bool':
case 'boolean':
return 'boolean';
case 'int':
return 'integer';
case 'text':
case 'string':
default:
return 'string';
}
} // end getParamTemplateByType
private function getParamChunksFromLine($line)
{
$paramChunks = explode(' ', $line);
$paramChunks = array_filter($paramChunks, function($val) {
return $val !== '';
});
unset($paramChunks[0]);
return $paramChunks;
} // end getParamChunksFromLine
private function filterDocBlock($docs)
{
foreach ($docs as &$line) {
$line = preg_replace('~\s*\*\s*~', '', $line);
$line = preg_replace('~^/$~', '', $line);
}
$docs = array_values(array_filter($docs));
return $docs;
} // end filterDocBlock
private function generateEndpointKey($class)
{
$disabledNamespaces = $this->config->get('yaro.apidocs.disabled_namespaces', []);
$chunks = explode('\\', $class);
foreach ($chunks as $index => $chunk) {
if (in_array($chunk, $disabledNamespaces)) {
unset($chunks[$index]);
continue;
}
$chunk = preg_replace('~Controller$~', '', $chunk);
if ($chunk) {
$chunk = $this->splitCamelCaseToWords($chunk);
$chunks[$index] = implode(' ', $chunk);
}
}
return implode('.', $chunks);
} // end generateEndpointKey
private function getSortedEndpoints($endpoints)
{
ksort($endpoints);
$sorted = array();
foreach ($endpoints as $key => $val) {
$this->ins($sorted, explode('.', $key), $val);
}
return $sorted;
} // end getSortedEndpoints
private function getUriParams($route)
{
preg_match_all('~{(\w+)}~', $this->getRouteParam($route, 'uri'), $matches);
return isset($matches[1]) ? $matches[1] : [];
} // end getUriParams
private function generateHashForUrl($key, $route, $method)
{
$path = preg_replace('~\s+~', '-', $key);
$httpMethod = $this->getRouteParam($route, 'methods.0');
$classMethod = implode('-', $this->splitCamelCaseToWords($method));
$hash = $path .'::'. $httpMethod .'::'. $classMethod;
return strtolower($hash);
} // end generateHashForUrl
private function splitCamelCaseToWords($chunk)
{
$splitCamelCaseRegexp = '/(?#! splitCamelCase Rev:20140412)
# Split camelCase "words". Two global alternatives. Either g1of2:
(?<=[a-z]) # Position is after a lowercase,
(?=[A-Z]) # and before an uppercase letter.
| (?<=[A-Z]) # Or g2of2; Position is after uppercase,
(?=[A-Z][a-z]) # and before upper-then-lower case.
/x';
return preg_split($splitCamelCaseRegexp, $chunk);
} // end splitCamelCaseToWords
private function getRouteParam($route, $param)
{
$route = (array) $route;
$prefix = chr(0).'*'.chr(0);
return $this->arrayGet(
$route,
$prefix.$param,
$this->arrayGet($route, $param)
);
} // end getRouteParam
private function ins(&$ary, $keys, $val)
{
$keys ?
$this->ins($ary[array_shift($keys)], $keys, $val) :
$ary = $val;
} // end ins
private function arrayGet($array, $key, $default = null)
{
if (is_null($key)) {
return $array;
}
if (isset($array[$key])) {
return $array[$key];
}
foreach (explode('.', $key) as $segment) {
if (!is_array($array) || ! array_key_exists($segment, $array)) {
return $default;
}
$array = $array[$segment];
}
return $array;
}
}