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