3 namespace BookStack\Api;
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;
12 use ReflectionException;
15 class ApiDocsGenerator
17 protected $reflectionClasses = [];
18 protected $controllerClasses = [];
21 * Load the docs form the cache if existing
22 * otherwise generate and store in the cache.
24 public static function generateConsideringCache(): Collection
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);
31 $docs = (new static())->generate();
32 Cache::put($cacheKey, $docs, 60 * 24);
39 * Generate API documentation.
41 protected function generate(): Collection
43 $apiRoutes = $this->getFlatApiRoutes();
44 $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
45 $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
46 $apiRoutes = $apiRoutes->groupBy('base_model');
52 * Load any API details stored in static files.
54 protected function loadDetailsFromFiles(Collection $routes): Collection
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;
69 * Load any details we can fetch from the controller and its methods.
71 protected function loadDetailsFromControllers(Collection $routes): Collection
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']);
84 * Load body params and their rules by inspecting the given class and method name.
86 * @throws BindingResolutionException
88 protected function getBodyParamsFromClass(string $className, string $methodName): ?array
90 /** @var ApiController $class */
91 $class = $this->controllerClasses[$className] ?? null;
92 if ($class === null) {
93 $class = app()->make($className);
94 $this->controllerClasses[$className] = $class;
97 $rules = $class->getValdationRules()[$methodName] ?? [];
98 foreach ($rules as $param => $ruleString) {
99 $rules[$param] = explode('|', $ruleString);
102 return count($rules) > 0 ? $rules : null;
106 * Parse out the description text from a class method comment.
108 protected function parseDescriptionFromMethodComment(string $comment)
111 preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
113 return implode(' ', $matches[1] ?? []);
117 * Get a reflection method from the given class name and method name.
119 * @throws ReflectionException
121 protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
123 $class = $this->reflectionClasses[$className] ?? null;
124 if ($class === null) {
125 $class = new ReflectionClass($className);
126 $this->reflectionClasses[$className] = $class;
129 return $class->getMethod($methodName);
133 * Get the system API routes, formatted into a flat collection.
135 protected function getFlatApiRoutes(): Collection
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;
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,