]> BookStack Code Mirror - bookstack/blob - app/Api/ApiDocsGenerator.php
fix(wysiwyg): preserves line feeds in code block mode
[bookstack] / app / Api / ApiDocsGenerator.php
1 <?php
2
3 namespace BookStack\Api;
4
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;
11 use ReflectionClass;
12 use ReflectionException;
13 use ReflectionMethod;
14
15 class ApiDocsGenerator
16 {
17     protected $reflectionClasses = [];
18     protected $controllerClasses = [];
19
20     /**
21      * Load the docs form the cache if existing
22      * otherwise generate and store in the cache.
23      */
24     public static function generateConsideringCache(): Collection
25     {
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);
30         } else {
31             $docs = (new ApiDocsGenerator())->generate();
32             Cache::put($cacheKey, $docs, 60 * 24);
33         }
34
35         return $docs;
36     }
37
38     /**
39      * Generate API documentation.
40      */
41     protected function generate(): Collection
42     {
43         $apiRoutes = $this->getFlatApiRoutes();
44         $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
45         $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
46         $apiRoutes = $apiRoutes->groupBy('base_model');
47
48         return $apiRoutes;
49     }
50
51     /**
52      * Load any API details stored in static files.
53      */
54     protected function loadDetailsFromFiles(Collection $routes): Collection
55     {
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);
64                         continue 2;
65                     }
66                 }
67                 $route["example_{$exampleType}"] = null;
68             }
69
70             return $route;
71         });
72     }
73
74     /**
75      * Load any details we can fetch from the controller and its methods.
76      */
77     protected function loadDetailsFromControllers(Collection $routes): Collection
78     {
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']);
84
85             return $route;
86         });
87     }
88
89     /**
90      * Load body params and their rules by inspecting the given class and method name.
91      *
92      * @throws BindingResolutionException
93      */
94     protected function getBodyParamsFromClass(string $className, string $methodName): ?array
95     {
96         /** @var ApiController $class */
97         $class = $this->controllerClasses[$className] ?? null;
98         if ($class === null) {
99             $class = app()->make($className);
100             $this->controllerClasses[$className] = $class;
101         }
102
103         $rules = $class->getValdationRules()[$methodName] ?? [];
104
105         return empty($rules) ? null : $rules;
106     }
107
108     /**
109      * Parse out the description text from a class method comment.
110      */
111     protected function parseDescriptionFromMethodComment(string $comment): string
112     {
113         $matches = [];
114         preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
115
116         return implode(' ', $matches[1] ?? []);
117     }
118
119     /**
120      * Get a reflection method from the given class name and method name.
121      *
122      * @throws ReflectionException
123      */
124     protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
125     {
126         $class = $this->reflectionClasses[$className] ?? null;
127         if ($class === null) {
128             $class = new ReflectionClass($className);
129             $this->reflectionClasses[$className] = $class;
130         }
131
132         return $class->getMethod($methodName);
133     }
134
135     /**
136      * Get the system API routes, formatted into a flat collection.
137      */
138     protected function getFlatApiRoutes(): Collection
139     {
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;
146
147             return [
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,
155             ];
156         });
157     }
158 }