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