3 namespace BookStack\Api;
5 use BookStack\App\AppVersion;
6 use BookStack\Http\ApiController;
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;
15 use ReflectionException;
18 class ApiDocsGenerator
20 protected array $reflectionClasses = [];
21 protected array $controllerClasses = [];
24 * Load the docs form the cache if existing
25 * otherwise generate and store in the cache.
27 public static function generateConsideringCache(): Collection
29 $appVersion = AppVersion::get();
30 $cacheKey = 'api-docs::' . $appVersion;
31 $isProduction = config('app.env') === 'production';
32 $cacheVal = $isProduction ? Cache::get($cacheKey) : null;
34 if (!is_null($cacheVal)) {
38 $docs = (new ApiDocsGenerator())->generate();
39 Cache::put($cacheKey, $docs, 60 * 24);
45 * Generate API documentation.
47 protected function generate(): Collection
49 $apiRoutes = $this->getFlatApiRoutes();
50 $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
51 $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
52 $apiRoutes = $apiRoutes->groupBy('base_model');
58 * Load any API details stored in static files.
60 protected function loadDetailsFromFiles(Collection $routes): Collection
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);
73 $route["example_{$exampleType}"] = null;
81 * Load any details we can fetch from the controller and its methods.
83 protected function loadDetailsFromControllers(Collection $routes): Collection
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']);
96 * Load body params and their rules by inspecting the given class and method name.
98 * @throws BindingResolutionException
100 protected function getBodyParamsFromClass(string $className, string $methodName): ?array
102 /** @var ApiController $class */
103 $class = $this->controllerClasses[$className] ?? null;
104 if ($class === null) {
105 $class = app()->make($className);
106 $this->controllerClasses[$className] = $class;
109 $rules = collect($class->getValidationRules()[$methodName] ?? [])->map(function ($validations) {
110 return array_map(function ($validation) {
111 return $this->getValidationAsString($validation);
115 return empty($rules) ? null : $rules;
119 * Convert the given validation message to a readable string.
121 protected function getValidationAsString($validation): string
123 if (is_string($validation)) {
127 if (is_object($validation) && method_exists($validation, '__toString')) {
128 return strval($validation);
131 if ($validation instanceof Password) {
135 $class = get_class($validation);
137 throw new Exception("Cannot provide string representation of rule for class: {$class}");
141 * Parse out the description text from a class method comment.
143 protected function parseDescriptionFromMethodComment(string $comment): string
146 preg_match_all('/^\s*?\*\s?($|((?![\/@\s]).*?))$/m', $comment, $matches);
148 $text = implode(' ', $matches[1] ?? []);
149 return str_replace(' ', "\n", $text);
153 * Get a reflection method from the given class name and method name.
155 * @throws ReflectionException
157 protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
159 $class = $this->reflectionClasses[$className] ?? null;
160 if ($class === null) {
161 $class = new ReflectionClass($className);
162 $this->reflectionClasses[$className] = $class;
165 return $class->getMethod($methodName);
169 * Get the system API routes, formatted into a flat collection.
171 protected function getFlatApiRoutes(): Collection
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;
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,