]> BookStack Code Mirror - bookstack/blob - app/Api/ApiDocsGenerator.php
Added testing for our request method overrides
[bookstack] / app / Api / ApiDocsGenerator.php
1 <?php
2
3 namespace BookStack\Api;
4
5 use BookStack\Http\Controllers\Api\ApiController;
6 use Exception;
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;
13 use ReflectionClass;
14 use ReflectionException;
15 use ReflectionMethod;
16
17 class ApiDocsGenerator
18 {
19     protected $reflectionClasses = [];
20     protected $controllerClasses = [];
21
22     /**
23      * Load the docs form the cache if existing
24      * otherwise generate and store in the cache.
25      */
26     public static function generateConsideringCache(): Collection
27     {
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);
32         } else {
33             $docs = (new ApiDocsGenerator())->generate();
34             Cache::put($cacheKey, $docs, 60 * 24);
35         }
36
37         return $docs;
38     }
39
40     /**
41      * Generate API documentation.
42      */
43     protected function generate(): Collection
44     {
45         $apiRoutes = $this->getFlatApiRoutes();
46         $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
47         $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
48         $apiRoutes = $apiRoutes->groupBy('base_model');
49
50         return $apiRoutes;
51     }
52
53     /**
54      * Load any API details stored in static files.
55      */
56     protected function loadDetailsFromFiles(Collection $routes): Collection
57     {
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);
66                         continue 2;
67                     }
68                 }
69                 $route["example_{$exampleType}"] = null;
70             }
71
72             return $route;
73         });
74     }
75
76     /**
77      * Load any details we can fetch from the controller and its methods.
78      */
79     protected function loadDetailsFromControllers(Collection $routes): Collection
80     {
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']);
86
87             return $route;
88         });
89     }
90
91     /**
92      * Load body params and their rules by inspecting the given class and method name.
93      *
94      * @throws BindingResolutionException
95      */
96     protected function getBodyParamsFromClass(string $className, string $methodName): ?array
97     {
98         /** @var ApiController $class */
99         $class = $this->controllerClasses[$className] ?? null;
100         if ($class === null) {
101             $class = app()->make($className);
102             $this->controllerClasses[$className] = $class;
103         }
104
105         $rules = collect($class->getValidationRules()[$methodName] ?? [])->map(function ($validations) {
106             return array_map(function ($validation) {
107                 return $this->getValidationAsString($validation);
108             }, $validations);
109         })->toArray();
110
111         return empty($rules) ? null : $rules;
112     }
113
114     /**
115      * Convert the given validation message to a readable string.
116      */
117     protected function getValidationAsString($validation): string
118     {
119         if (is_string($validation)) {
120             return $validation;
121         }
122
123         if (is_object($validation) && method_exists($validation, '__toString')) {
124             return strval($validation);
125         }
126
127         if ($validation instanceof Password) {
128             return 'min:8';
129         }
130
131         $class = get_class($validation);
132
133         throw new Exception("Cannot provide string representation of rule for class: {$class}");
134     }
135
136     /**
137      * Parse out the description text from a class method comment.
138      */
139     protected function parseDescriptionFromMethodComment(string $comment): string
140     {
141         $matches = [];
142         preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
143
144         return implode(' ', $matches[1] ?? []);
145     }
146
147     /**
148      * Get a reflection method from the given class name and method name.
149      *
150      * @throws ReflectionException
151      */
152     protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
153     {
154         $class = $this->reflectionClasses[$className] ?? null;
155         if ($class === null) {
156             $class = new ReflectionClass($className);
157             $this->reflectionClasses[$className] = $class;
158         }
159
160         return $class->getMethod($methodName);
161     }
162
163     /**
164      * Get the system API routes, formatted into a flat collection.
165      */
166     protected function getFlatApiRoutes(): Collection
167     {
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;
174
175             return [
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,
183             ];
184         });
185     }
186 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.