]> BookStack Code Mirror - bookstack/blob - app/Api/ApiDocsGenerator.php
Vectors: Added command to regenerate for all
[bookstack] / app / Api / ApiDocsGenerator.php
1 <?php
2
3 namespace BookStack\Api;
4
5 use BookStack\Http\ApiController;
6 use Exception;
7 use Illuminate\Contracts\Container\BindingResolutionException;
8 use Illuminate\Support\Collection;
9 use Illuminate\Support\Facades\Cache;
10 use Illuminate\Support\Facades\Route;
11 use Illuminate\Support\Str;
12 use Illuminate\Validation\Rules\Password;
13 use ReflectionClass;
14 use ReflectionException;
15 use ReflectionMethod;
16
17 class ApiDocsGenerator
18 {
19     protected array $reflectionClasses = [];
20     protected array $controllerClasses = [];
21
22     /**
23      * Load the docs form the cache if existing
24      * otherwise generate and store in the cache.
25      */
26     public static function generateConsideringCache(): Collection
27     {
28         $appVersion = trim(file_get_contents(base_path('version')));
29         $cacheKey = 'api-docs::' . $appVersion;
30         $isProduction = config('app.env') === 'production';
31         $cacheVal = $isProduction ? Cache::get($cacheKey) : null;
32
33         if (!is_null($cacheVal)) {
34             return $cacheVal;
35         }
36
37         $docs = (new ApiDocsGenerator())->generate();
38         Cache::put($cacheKey, $docs, 60 * 24);
39
40         return $docs;
41     }
42
43     /**
44      * Generate API documentation.
45      */
46     protected function generate(): Collection
47     {
48         $apiRoutes = $this->getFlatApiRoutes();
49         $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
50         $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
51         $apiRoutes = $apiRoutes->groupBy('base_model');
52
53         return $apiRoutes;
54     }
55
56     /**
57      * Load any API details stored in static files.
58      */
59     protected function loadDetailsFromFiles(Collection $routes): Collection
60     {
61         return $routes->map(function (array $route) {
62             $exampleTypes = ['request', 'response'];
63             $fileTypes = ['json', 'http'];
64             foreach ($exampleTypes as $exampleType) {
65                 foreach ($fileTypes as $fileType) {
66                     $exampleFile = base_path("dev/api/{$exampleType}s/{$route['name']}." . $fileType);
67                     if (file_exists($exampleFile)) {
68                         $route["example_{$exampleType}"] = file_get_contents($exampleFile);
69                         continue 2;
70                     }
71                 }
72                 $route["example_{$exampleType}"] = null;
73             }
74
75             return $route;
76         });
77     }
78
79     /**
80      * Load any details we can fetch from the controller and its methods.
81      */
82     protected function loadDetailsFromControllers(Collection $routes): Collection
83     {
84         return $routes->map(function (array $route) {
85             $method = $this->getReflectionMethod($route['controller'], $route['controller_method']);
86             $comment = $method->getDocComment();
87             $route['description'] = $comment ? $this->parseDescriptionFromMethodComment($comment) : null;
88             $route['body_params'] = $this->getBodyParamsFromClass($route['controller'], $route['controller_method']);
89
90             return $route;
91         });
92     }
93
94     /**
95      * Load body params and their rules by inspecting the given class and method name.
96      *
97      * @throws BindingResolutionException
98      */
99     protected function getBodyParamsFromClass(string $className, string $methodName): ?array
100     {
101         /** @var ApiController $class */
102         $class = $this->controllerClasses[$className] ?? null;
103         if ($class === null) {
104             $class = app()->make($className);
105             $this->controllerClasses[$className] = $class;
106         }
107
108         $rules = collect($class->getValidationRules()[$methodName] ?? [])->map(function ($validations) {
109             return array_map(function ($validation) {
110                 return $this->getValidationAsString($validation);
111             }, $validations);
112         })->toArray();
113
114         return empty($rules) ? null : $rules;
115     }
116
117     /**
118      * Convert the given validation message to a readable string.
119      */
120     protected function getValidationAsString($validation): string
121     {
122         if (is_string($validation)) {
123             return $validation;
124         }
125
126         if (is_object($validation) && method_exists($validation, '__toString')) {
127             return strval($validation);
128         }
129
130         if ($validation instanceof Password) {
131             return 'min:8';
132         }
133
134         $class = get_class($validation);
135
136         throw new Exception("Cannot provide string representation of rule for class: {$class}");
137     }
138
139     /**
140      * Parse out the description text from a class method comment.
141      */
142     protected function parseDescriptionFromMethodComment(string $comment): string
143     {
144         $matches = [];
145         preg_match_all('/^\s*?\*\s?($|((?![\/@\s]).*?))$/m', $comment, $matches);
146
147         $text = implode(' ', $matches[1] ?? []);
148         return str_replace('  ', "\n", $text);
149     }
150
151     /**
152      * Get a reflection method from the given class name and method name.
153      *
154      * @throws ReflectionException
155      */
156     protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
157     {
158         $class = $this->reflectionClasses[$className] ?? null;
159         if ($class === null) {
160             $class = new ReflectionClass($className);
161             $this->reflectionClasses[$className] = $class;
162         }
163
164         return $class->getMethod($methodName);
165     }
166
167     /**
168      * Get the system API routes, formatted into a flat collection.
169      */
170     protected function getFlatApiRoutes(): Collection
171     {
172         return collect(Route::getRoutes()->getRoutes())->filter(function ($route) {
173             return strpos($route->uri, 'api/') === 0;
174         })->map(function ($route) {
175             [$controller, $controllerMethod] = explode('@', $route->action['uses']);
176             $baseModelName = explode('.', explode('/', $route->uri)[1])[0];
177             $shortName = $baseModelName . '-' . $controllerMethod;
178
179             return [
180                 'name'                    => $shortName,
181                 'uri'                     => $route->uri,
182                 'method'                  => $route->methods[0],
183                 'controller'              => $controller,
184                 'controller_method'       => $controllerMethod,
185                 'controller_method_kebab' => Str::kebab($controllerMethod),
186                 'base_model'              => $baseModelName,
187             ];
188         });
189     }
190 }