]> BookStack Code Mirror - bookstack/blob - app/Api/ApiDocsGenerator.php
Move logFailedAccess into Activity
[bookstack] / app / Api / ApiDocsGenerator.php
1 <?php namespace BookStack\Api;
2
3 use BookStack\Http\Controllers\Api\ApiController;
4 use Illuminate\Support\Collection;
5 use Illuminate\Support\Facades\Route;
6 use ReflectionClass;
7 use ReflectionException;
8 use ReflectionMethod;
9
10 class ApiDocsGenerator
11 {
12
13     protected $reflectionClasses = [];
14     protected $controllerClasses = [];
15
16     /**
17      * Generate API documentation.
18      */
19     public function generate(): Collection
20     {
21         $apiRoutes = $this->getFlatApiRoutes();
22         $apiRoutes = $this->loadDetailsFromControllers($apiRoutes);
23         $apiRoutes = $this->loadDetailsFromFiles($apiRoutes);
24         $apiRoutes = $apiRoutes->groupBy('base_model');
25         return $apiRoutes;
26     }
27
28     /**
29      * Load any API details stored in static files.
30      */
31     protected function loadDetailsFromFiles(Collection $routes): Collection
32     {
33         return $routes->map(function (array $route) {
34             $exampleTypes = ['request', 'response'];
35             foreach ($exampleTypes as $exampleType) {
36                 $exampleFile = base_path("dev/api/{$exampleType}s/{$route['name']}.json");
37                 $exampleContent = file_exists($exampleFile) ? file_get_contents($exampleFile) : null;
38                 $route["example_{$exampleType}"] = $exampleContent;
39             }
40             return $route;
41         });
42     }
43
44     /**
45      * Load any details we can fetch from the controller and its methods.
46      */
47     protected function loadDetailsFromControllers(Collection $routes): Collection
48     {
49         return $routes->map(function (array $route) {
50             $method = $this->getReflectionMethod($route['controller'], $route['controller_method']);
51             $comment = $method->getDocComment();
52             $route['description'] = $comment ? $this->parseDescriptionFromMethodComment($comment) : null;
53             $route['body_params'] = $this->getBodyParamsFromClass($route['controller'], $route['controller_method']);
54             return $route;
55         });
56     }
57
58     /**
59      * Load body params and their rules by inspecting the given class and method name.
60      * @throws \Illuminate\Contracts\Container\BindingResolutionException
61      */
62     protected function getBodyParamsFromClass(string $className, string $methodName): ?array
63     {
64         /** @var ApiController $class */
65         $class = $this->controllerClasses[$className] ?? null;
66         if ($class === null) {
67             $class = app()->make($className);
68             $this->controllerClasses[$className] = $class;
69         }
70
71         $rules = $class->getValdationRules()[$methodName] ?? [];
72         foreach ($rules as $param => $ruleString) {
73             $rules[$param] = explode('|', $ruleString);
74         }
75         return count($rules) > 0 ? $rules : null;
76     }
77
78     /**
79      * Parse out the description text from a class method comment.
80      */
81     protected function parseDescriptionFromMethodComment(string $comment)
82     {
83         $matches = [];
84         preg_match_all('/^\s*?\*\s((?![@\s]).*?)$/m', $comment, $matches);
85         return implode(' ', $matches[1] ?? []);
86     }
87
88     /**
89      * Get a reflection method from the given class name and method name.
90      * @throws ReflectionException
91      */
92     protected function getReflectionMethod(string $className, string $methodName): ReflectionMethod
93     {
94         $class = $this->reflectionClasses[$className] ?? null;
95         if ($class === null) {
96             $class = new ReflectionClass($className);
97             $this->reflectionClasses[$className] = $class;
98         }
99
100         return $class->getMethod($methodName);
101     }
102
103     /**
104      * Get the system API routes, formatted into a flat collection.
105      */
106     protected function getFlatApiRoutes(): Collection
107     {
108         return collect(Route::getRoutes()->getRoutes())->filter(function ($route) {
109             return strpos($route->uri, 'api/') === 0;
110         })->map(function ($route) {
111             [$controller, $controllerMethod] = explode('@', $route->action['uses']);
112             $baseModelName = explode('.', explode('/', $route->uri)[1])[0];
113             $shortName = $baseModelName . '-' . $controllerMethod;
114             return [
115                 'name' => $shortName,
116                 'uri' => $route->uri,
117                 'method' => $route->methods[0],
118                 'controller' => $controller,
119                 'controller_method' => $controllerMethod,
120                 'base_model' => $baseModelName,
121             ];
122         });
123     }
124
125 }