]> BookStack Code Mirror - bookstack/blob - app/Api/ApiDocsGenerator.php
Apply fixes from StyleCI
[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 static())->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         foreach ($rules as $param => $ruleString) {
99             $rules[$param] = explode('|', $ruleString);
100         }
101
102         return count($rules) > 0 ? $rules : null;
103     }
104
105     /**
106      * Parse out the description text from a class method comment.
107      */
108     protected function parseDescriptionFromMethodComment(string $comment)
109     {
110         $matches = [];
111         preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
112
113         return implode(' ', $matches[1] ?? []);
114     }
115
116     /**
117      * Get a reflection method from the given class name and method name.
118      *
119      * @throws ReflectionException
120      */
121     protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
122     {
123         $class = $this->reflectionClasses[$className] ?? null;
124         if ($class === null) {
125             $class = new ReflectionClass($className);
126             $this->reflectionClasses[$className] = $class;
127         }
128
129         return $class->getMethod($methodName);
130     }
131
132     /**
133      * Get the system API routes, formatted into a flat collection.
134      */
135     protected function getFlatApiRoutes(): Collection
136     {
137         return collect(Route::getRoutes()->getRoutes())->filter(function ($route) {
138             return strpos($route->uri, 'api/') === 0;
139         })->map(function ($route) {
140             [$controller, $controllerMethod] = explode('@', $route->action['uses']);
141             $baseModelName = explode('.', explode('/', $route->uri)[1])[0];
142             $shortName = $baseModelName . '-' . $controllerMethod;
143
144             return [
145                 'name'                    => $shortName,
146                 'uri'                     => $route->uri,
147                 'method'                  => $route->methods[0],
148                 'controller'              => $controller,
149                 'controller_method'       => $controllerMethod,
150                 'controller_method_kebab' => Str::kebab($controllerMethod),
151                 'base_model'              => $baseModelName,
152             ];
153         });
154     }
155 }