3 namespace BookStack\Api;
5 use BookStack\Http\Controllers\Api\ApiController;
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;
14 use ReflectionException;
17 class ApiDocsGenerator
19 protected $reflectionClasses = [];
20 protected $controllerClasses = [];
23 * Load the docs form the cache if existing
24 * otherwise generate and store in the cache.
26 public static function generateConsideringCache(): Collection
28 $appVersion = trim(file_get_contents(base_path('version')));
29 $cacheKey = 'api-docs::' . $appVersion;
30 if (Cache::has($cacheKey) && config('app.env') === 'production') {
31 $docs = Cache::get($cacheKey);
33 $docs = (new ApiDocsGenerator())->generate();
34 Cache::put($cacheKey, $docs, 60 * 24);
41 * Generate API documentation.
43 protected function generate(): Collection
45 $apiRoutes = $this->getFlatApiRoutes();
46 $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
47 $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
48 $apiRoutes = $apiRoutes->groupBy('base_model');
54 * Load any API details stored in static files.
56 protected function loadDetailsFromFiles(Collection $routes): Collection
58 return $routes->map(function (array $route) {
59 $exampleTypes = ['request', 'response'];
60 $fileTypes = ['json', 'http'];
61 foreach ($exampleTypes as $exampleType) {
62 foreach ($fileTypes as $fileType) {
63 $exampleFile = base_path("dev/api/{$exampleType}s/{$route['name']}." . $fileType);
64 if (file_exists($exampleFile)) {
65 $route["example_{$exampleType}"] = file_get_contents($exampleFile);
69 $route["example_{$exampleType}"] = null;
77 * Load any details we can fetch from the controller and its methods.
79 protected function loadDetailsFromControllers(Collection $routes): Collection
81 return $routes->map(function (array $route) {
82 $method = $this->getReflectionMethod($route['controller'], $route['controller_method']);
83 $comment = $method->getDocComment();
84 $route['description'] = $comment ? $this->parseDescriptionFromMethodComment($comment) : null;
85 $route['body_params'] = $this->getBodyParamsFromClass($route['controller'], $route['controller_method']);
92 * Load body params and their rules by inspecting the given class and method name.
94 * @throws BindingResolutionException
96 protected function getBodyParamsFromClass(string $className, string $methodName): ?array
98 /** @var ApiController $class */
99 $class = $this->controllerClasses[$className] ?? null;
100 if ($class === null) {
101 $class = app()->make($className);
102 $this->controllerClasses[$className] = $class;
105 $rules = collect($class->getValidationRules()[$methodName] ?? [])->map(function ($validations) {
106 return array_map(function ($validation) {
107 return $this->getValidationAsString($validation);
111 return empty($rules) ? null : $rules;
115 * Convert the given validation message to a readable string.
117 protected function getValidationAsString($validation): string
119 if (is_string($validation)) {
123 if (is_object($validation) && method_exists($validation, '__toString')) {
124 return strval($validation);
127 if ($validation instanceof Password) {
131 $class = get_class($validation);
133 throw new Exception("Cannot provide string representation of rule for class: {$class}");
137 * Parse out the description text from a class method comment.
139 protected function parseDescriptionFromMethodComment(string $comment): string
142 preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
144 return implode(' ', $matches[1] ?? []);
148 * Get a reflection method from the given class name and method name.
150 * @throws ReflectionException
152 protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
154 $class = $this->reflectionClasses[$className] ?? null;
155 if ($class === null) {
156 $class = new ReflectionClass($className);
157 $this->reflectionClasses[$className] = $class;
160 return $class->getMethod($methodName);
164 * Get the system API routes, formatted into a flat collection.
166 protected function getFlatApiRoutes(): Collection
168 return collect(Route::getRoutes()->getRoutes())->filter(function ($route) {
169 return strpos($route->uri, 'api/') === 0;
170 })->map(function ($route) {
171 [$controller, $controllerMethod] = explode('@', $route->action['uses']);
172 $baseModelName = explode('.', explode('/', $route->uri)[1])[0];
173 $shortName = $baseModelName . '-' . $controllerMethod;
176 'name' => $shortName,
177 'uri' => $route->uri,
178 'method' => $route->methods[0],
179 'controller' => $controller,
180 'controller_method' => $controllerMethod,
181 'controller_method_kebab' => Str::kebab($controllerMethod),
182 'base_model' => $baseModelName,