]> BookStack Code Mirror - bookstack/blob - app/Api/ApiDocsGenerator.php
Applied StyleCI changes, added php/larastan to attribution
[bookstack] / app / Api / ApiDocsGenerator.php
1 <?php
2
3 namespace BookStack\Api;
4
5 use BookStack\Http\Controllers\Api\ApiController;
6 use Illuminate\Contracts\Container\BindingResolutionException;
7 use Illuminate\Support\Collection;
8 use Illuminate\Support\Facades\Cache;
9 use Illuminate\Support\Facades\Route;
10 use Illuminate\Support\Str;
11 use ReflectionClass;
12 use ReflectionException;
13 use ReflectionMethod;
14
15 class ApiDocsGenerator
16 {
17     protected $reflectionClasses = [];
18     protected $controllerClasses = [];
19
20     /**
21      * Load the docs form the cache if existing
22      * otherwise generate and store in the cache.
23      */
24     public static function generateConsideringCache(): Collection
25     {
26         $appVersion = trim(file_get_contents(base_path('version')));
27         $cacheKey = 'api-docs::' . $appVersion;
28         if (Cache::has($cacheKey) && config('app.env') === 'production') {
29             $docs = Cache::get($cacheKey);
30         } else {
31             $docs = (new ApiDocsGenerator())->generate();
32             Cache::put($cacheKey, $docs, 60 * 24);
33         }
34
35         return $docs;
36     }
37
38     /**
39      * Generate API documentation.
40      */
41     protected function generate(): Collection
42     {
43         $apiRoutes = $this->getFlatApiRoutes();
44         $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
45         $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
46         $apiRoutes = $apiRoutes->groupBy('base_model');
47
48         return $apiRoutes;
49     }
50
51     /**
52      * Load any API details stored in static files.
53      */
54     protected function loadDetailsFromFiles(Collection $routes): Collection
55     {
56         return $routes->map(function (array $route) {
57             $exampleTypes = ['request', 'response'];
58             foreach ($exampleTypes as $exampleType) {
59                 $exampleFile = base_path("dev/api/{$exampleType}s/{$route['name']}.json");
60                 $exampleContent = file_exists($exampleFile) ? file_get_contents($exampleFile) : null;
61                 $route["example_{$exampleType}"] = $exampleContent;
62             }
63
64             return $route;
65         });
66     }
67
68     /**
69      * Load any details we can fetch from the controller and its methods.
70      */
71     protected function loadDetailsFromControllers(Collection $routes): Collection
72     {
73         return $routes->map(function (array $route) {
74             $method = $this->getReflectionMethod($route['controller'], $route['controller_method']);
75             $comment = $method->getDocComment();
76             $route['description'] = $comment ? $this->parseDescriptionFromMethodComment($comment) : null;
77             $route['body_params'] = $this->getBodyParamsFromClass($route['controller'], $route['controller_method']);
78
79             return $route;
80         });
81     }
82
83     /**
84      * Load body params and their rules by inspecting the given class and method name.
85      *
86      * @throws BindingResolutionException
87      */
88     protected function getBodyParamsFromClass(string $className, string $methodName): ?array
89     {
90         /** @var ApiController $class */
91         $class = $this->controllerClasses[$className] ?? null;
92         if ($class === null) {
93             $class = app()->make($className);
94             $this->controllerClasses[$className] = $class;
95         }
96
97         $rules = $class->getValdationRules()[$methodName] ?? [];
98
99         return empty($rules) ? null : $rules;
100     }
101
102     /**
103      * Parse out the description text from a class method comment.
104      */
105     protected function parseDescriptionFromMethodComment(string $comment): string
106     {
107         $matches = [];
108         preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
109
110         return implode(' ', $matches[1] ?? []);
111     }
112
113     /**
114      * Get a reflection method from the given class name and method name.
115      *
116      * @throws ReflectionException
117      */
118     protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
119     {
120         $class = $this->reflectionClasses[$className] ?? null;
121         if ($class === null) {
122             $class = new ReflectionClass($className);
123             $this->reflectionClasses[$className] = $class;
124         }
125
126         return $class->getMethod($methodName);
127     }
128
129     /**
130      * Get the system API routes, formatted into a flat collection.
131      */
132     protected function getFlatApiRoutes(): Collection
133     {
134         return collect(Route::getRoutes()->getRoutes())->filter(function ($route) {
135             return strpos($route->uri, 'api/') === 0;
136         })->map(function ($route) {
137             [$controller, $controllerMethod] = explode('@', $route->action['uses']);
138             $baseModelName = explode('.', explode('/', $route->uri)[1])[0];
139             $shortName = $baseModelName . '-' . $controllerMethod;
140
141             return [
142                 'name'                    => $shortName,
143                 'uri'                     => $route->uri,
144                 'method'                  => $route->methods[0],
145                 'controller'              => $controller,
146                 'controller_method'       => $controllerMethod,
147                 'controller_method_kebab' => Str::kebab($controllerMethod),
148                 'base_model'              => $baseModelName,
149             ];
150         });
151     }
152 }