1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mpociot\ApiDoc\Extracting; |
4
|
|
|
|
5
|
|
|
use Illuminate\Routing\Route; |
6
|
|
|
use Mpociot\ApiDoc\Tools\Utils; |
7
|
|
|
use Mpociot\Reflection\DocBlock; |
8
|
|
|
use ReflectionClass; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class RouteDocBlocker |
12
|
|
|
* Utility class to help with retrieving doc blocks from route classes and methods. |
13
|
|
|
* Also caches them so repeated access is faster. |
14
|
|
|
*/ |
15
|
|
|
class RouteDocBlocker |
16
|
|
|
{ |
17
|
|
|
protected static $docBlocks = []; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param Route $route |
21
|
|
|
* |
22
|
|
|
* @throws \ReflectionException |
23
|
|
|
* @throws \Exception |
24
|
|
|
* |
25
|
|
|
* @return array<string, DocBlock> Method and class docblocks |
|
|
|
|
26
|
|
|
*/ |
27
|
|
|
public static function getDocBlocksFromRoute(Route $route): array |
28
|
|
|
{ |
29
|
|
|
list($className, $methodName) = Utils::getRouteClassAndMethodNames($route); |
30
|
|
|
$docBlocks = self::getCachedDocBlock($route, $className, $methodName); |
31
|
|
|
if ($docBlocks) { |
32
|
|
|
return $docBlocks; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$class = new ReflectionClass($className); |
36
|
|
|
|
37
|
|
|
if (! $class->hasMethod($methodName)) { |
38
|
|
|
throw new \Exception("Error while fetching docblock for route: Class $className does not contain method $methodName"); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$docBlocks = [ |
42
|
|
|
'method' => new DocBlock($class->getMethod($methodName)->getDocComment() ?: ''), |
43
|
|
|
'class' => new DocBlock($class->getDocComment() ?: ''), |
44
|
|
|
]; |
45
|
|
|
self::cacheDocBlocks($route, $className, $methodName, $docBlocks); |
46
|
|
|
|
47
|
|
|
return $docBlocks; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected static function getCachedDocBlock(Route $route, string $className, string $methodName) |
51
|
|
|
{ |
52
|
|
|
$routeId = self::getRouteCacheId($route, $className, $methodName); |
53
|
|
|
|
54
|
|
|
return self::$docBlocks[$routeId] ?? null; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
protected static function cacheDocBlocks(Route $route, string $className, string $methodName, array $docBlocks) |
58
|
|
|
{ |
59
|
|
|
$routeId = self::getRouteCacheId($route, $className, $methodName); |
60
|
|
|
self::$docBlocks[$routeId] = $docBlocks; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private static function getRouteCacheId(Route $route, string $className, string $methodName): string |
64
|
|
|
{ |
65
|
|
|
return $route->uri() |
66
|
|
|
. ':' |
67
|
|
|
. implode(array_diff($route->methods(), ['HEAD'])) |
68
|
|
|
. $className |
69
|
|
|
. $methodName; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.