Completed
Pull Request — master (#570)
by Marcel
01:55
created

RouteDocBlocker   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 56
rs 10
c 0
b 0
f 0

4 Methods

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