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 ApiDocsGenerator())->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 $fileTypes = ['json', 'http'];
59 foreach ($exampleTypes as $exampleType) {
60 foreach ($fileTypes as $fileType) {
61 $exampleFile = base_path("dev/api/{$exampleType}s/{$route['name']}." . $fileType);
62 if (file_exists($exampleFile)) {
63 $route["example_{$exampleType}"] = file_get_contents($exampleFile);
67 $route["example_{$exampleType}"] = null;
75 * Load any details we can fetch from the controller and its methods.
77 protected function loadDetailsFromControllers(Collection $routes): Collection
79 return $routes->map(function (array $route) {
80 $method = $this->getReflectionMethod($route['controller'], $route['controller_method']);
81 $comment = $method->getDocComment();
82 $route['description'] = $comment ? $this->parseDescriptionFromMethodComment($comment) : null;
83 $route['body_params'] = $this->getBodyParamsFromClass($route['controller'], $route['controller_method']);
90 * Load body params and their rules by inspecting the given class and method name.
92 * @throws BindingResolutionException
94 protected function getBodyParamsFromClass(string $className, string $methodName): ?array
96 /** @var ApiController $class */
97 $class = $this->controllerClasses[$className] ?? null;
98 if ($class === null) {
99 $class = app()->make($className);
100 $this->controllerClasses[$className] = $class;
103 $rules = $class->getValdationRules()[$methodName] ?? [];
105 return empty($rules) ? null : $rules;
109 * Parse out the description text from a class method comment.
111 protected function parseDescriptionFromMethodComment(string $comment): string
114 preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
116 return implode(' ', $matches[1] ?? []);
120 * Get a reflection method from the given class name and method name.
122 * @throws ReflectionException
124 protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
126 $class = $this->reflectionClasses[$className] ?? null;
127 if ($class === null) {
128 $class = new ReflectionClass($className);
129 $this->reflectionClasses[$className] = $class;
132 return $class->getMethod($methodName);
136 * Get the system API routes, formatted into a flat collection.
138 protected function getFlatApiRoutes(): Collection
140 return collect(Route::getRoutes()->getRoutes())->filter(function ($route) {
141 return strpos($route->uri, 'api/') === 0;
142 })->map(function ($route) {
143 [$controller, $controllerMethod] = explode('@', $route->action['uses']);
144 $baseModelName = explode('.', explode('/', $route->uri)[1])[0];
145 $shortName = $baseModelName . '-' . $controllerMethod;
148 'name' => $shortName,
149 'uri' => $route->uri,
150 'method' => $route->methods[0],
151 'controller' => $controller,
152 'controller_method' => $controllerMethod,
153 'controller_method_kebab' => Str::kebab($controllerMethod),
154 'base_model' => $baseModelName,