Completed
Pull Request — master (#570)
by
unknown
01:24
created

RouteDocBlocker::getRouteCacheId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
namespace Mpociot\ApiDoc\Tools;
4
5
use ReflectionClass;
6
use Illuminate\Routing\Route;
7
use Mpociot\Reflection\DocBlock;
8
9
class RouteDocBlocker
10
{
11
    protected static $docBlocks = [];
12
13
    /**
14
     * @param Route $route
15
     *
16
     * @return array<string, DocBlock> Method and class docblocks
0 ignored issues
show
Documentation introduced by
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

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.

Loading history...
17
     * @throws \ReflectionException
18
     */
19
    public static function getDocBlocksFromRoute(Route $route): array
20
    {
21
        list($className, $methodName) = Utils::getRouteClassAndMethodNames($route);
22
        $docBlocks = self::getCachedDocBlock($route, $className, $methodName);
23
        if ($docBlocks) {
24
            return $docBlocks;
25
        }
26
27
        $class = new ReflectionClass($className);
28
29
        if (! $class->hasMethod($methodName)) {
30
            throw new \Exception("Error while fetching docblock for route: Class $className does not contain method $methodName");
31
        }
32
33
        $docBlocks = [
34
            'method' => new DocBlock($class->getMethod($methodName)->getDocComment() ?: ''),
35
            'class' => new DocBlock($class->getDocComment() ?: ''),
36
        ];
37
        self::cacheDocBlocks($route, $className, $methodName, $docBlocks);
38
39
        return $docBlocks;
40
    }
41
42
    protected static function getCachedDocBlock(Route $route, string $className, string $methodName)
43
    {
44
        $routeId = self::getRouteCacheId($route, $className, $methodName);
45
46
        return self::$docBlocks[$routeId] ?? null;
47
    }
48
49
    protected static function cacheDocBlocks(Route $route, string $className, string $methodName, array $docBlocks)
50
    {
51
        $routeId = self::getRouteCacheId($route, $className, $methodName);
52
        self::$docBlocks[$routeId] = $docBlocks;
53
    }
54
55
    private static function getRouteCacheId(Route $route, string $className, string $methodName): string
56
    {
57
        return $route->uri()
58
            .':'
59
            .implode(array_diff($route->methods(), ['HEAD']))
60
            .$className
61
            .$methodName;
62
    }
63
}
64