GenerateDocumentation.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. namespace Mpociot\ApiDoc\Commands;
  3. use ReflectionClass;
  4. use Illuminate\Routing\Route;
  5. use Illuminate\Console\Command;
  6. use Mpociot\Reflection\DocBlock;
  7. use Illuminate\Support\Collection;
  8. use Mpociot\Documentarian\Documentarian;
  9. use Mpociot\ApiDoc\Postman\CollectionWriter;
  10. use Mpociot\ApiDoc\Generators\DingoGenerator;
  11. use Mpociot\ApiDoc\Generators\LaravelGenerator;
  12. use Mpociot\ApiDoc\Generators\AbstractGenerator;
  13. use Illuminate\Support\Facades\Route as RouteFacade;
  14. class GenerateDocumentation extends Command
  15. {
  16. /**
  17. * The name and signature of the console command.
  18. *
  19. * @var string
  20. */
  21. protected $signature = 'api:generate
  22. {--output=public/docs : The output path for the generated documentation}
  23. {--routeDomain= : The route domain (or domains) to use for generation}
  24. {--routePrefix= : The route prefix (or prefixes) to use for generation}
  25. {--routes=* : The route names to use for generation}
  26. {--middleware= : The middleware to use for generation}
  27. {--noResponseCalls : Disable API response calls}
  28. {--noPostmanCollection : Disable Postman collection creation}
  29. {--useMiddlewares : Use all configured route middlewares}
  30. {--authProvider=users : The authentication provider to use for API response calls}
  31. {--authGuard=web : The authentication guard to use for API response calls}
  32. {--actAsUserId= : The user ID to use for API response calls}
  33. {--router=laravel : The router to be used (Laravel or Dingo)}
  34. {--force : Force rewriting of existing routes}
  35. {--bindings= : Route Model Bindings}
  36. {--header=* : Custom HTTP headers to add to the example requests. Separate the header name and value with ":"}
  37. ';
  38. /**
  39. * The console command description.
  40. *
  41. * @var string
  42. */
  43. protected $description = 'Generate your API documentation from existing Laravel routes.';
  44. /**
  45. * Create a new command instance.
  46. *
  47. * @return void
  48. */
  49. public function __construct()
  50. {
  51. parent::__construct();
  52. }
  53. /**
  54. * Execute the console command.
  55. *
  56. * @return false|null
  57. */
  58. public function handle()
  59. {
  60. if ($this->option('router') === 'laravel') {
  61. $generator = new LaravelGenerator();
  62. } else {
  63. $generator = new DingoGenerator();
  64. }
  65. $allowedRoutes = $this->option('routes');
  66. $routeDomain = $this->option('routeDomain');
  67. $routePrefix = $this->option('routePrefix');
  68. $middleware = $this->option('middleware');
  69. $this->setUserToBeImpersonated($this->option('actAsUserId'));
  70. if ($routePrefix === null && $routeDomain === null && ! count($allowedRoutes) && $middleware === null) {
  71. $this->error('You must provide either a route prefix, a route domain, a route or a middleware to generate the documentation.');
  72. return false;
  73. }
  74. $generator->prepareMiddleware($this->option('useMiddlewares'));
  75. $routePrefixes = explode(',', $routePrefix ?: '*');
  76. $routeDomains = explode(',', $routeDomain ?: '*');
  77. $parsedRoutes = [];
  78. foreach ($routeDomains as $routeDomain) {
  79. foreach ($routePrefixes as $routePrefix) {
  80. $parsedRoutes += $this->processRoutes($generator, $allowedRoutes, $routeDomain, $routePrefix, $middleware);
  81. }
  82. }
  83. $parsedRoutes = collect($parsedRoutes)->groupBy('resource')->sort(function ($a, $b) {
  84. return strcmp($a->first()['resource'], $b->first()['resource']);
  85. });
  86. $this->writeMarkdown($parsedRoutes);
  87. }
  88. /**
  89. * @param Collection $parsedRoutes
  90. *
  91. * @return void
  92. */
  93. private function writeMarkdown($parsedRoutes)
  94. {
  95. $outputPath = $this->option('output');
  96. $targetFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'index.md';
  97. $compareFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'.compare.md';
  98. $prependFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'prepend.md';
  99. $appendFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'append.md';
  100. $infoText = view('apidoc::partials.info')
  101. ->with('outputPath', ltrim($outputPath, 'public/'))
  102. ->with('showPostmanCollectionButton', ! $this->option('noPostmanCollection'));
  103. $parsedRouteOutput = $parsedRoutes->map(function ($routeGroup) {
  104. return $routeGroup->map(function ($route) {
  105. $route['output'] = (string) view('apidoc::partials.route')->with('parsedRoute', $route)->render();
  106. return $route;
  107. });
  108. });
  109. $frontmatter = view('apidoc::partials.frontmatter');
  110. /*
  111. * In case the target file already exists, we should check if the documentation was modified
  112. * and skip the modified parts of the routes.
  113. */
  114. if (file_exists($targetFile) && file_exists($compareFile)) {
  115. $generatedDocumentation = file_get_contents($targetFile);
  116. $compareDocumentation = file_get_contents($compareFile);
  117. if (preg_match('/---(.*)---\\s<!-- START_INFO -->/is', $generatedDocumentation, $generatedFrontmatter)) {
  118. $frontmatter = trim($generatedFrontmatter[1], "\n");
  119. }
  120. $parsedRouteOutput->transform(function ($routeGroup) use ($generatedDocumentation, $compareDocumentation) {
  121. return $routeGroup->transform(function ($route) use ($generatedDocumentation, $compareDocumentation) {
  122. if (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $generatedDocumentation, $routeMatch)) {
  123. $routeDocumentationChanged = (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $compareDocumentation, $compareMatch) && $compareMatch[1] !== $routeMatch[1]);
  124. if ($routeDocumentationChanged === false || $this->option('force')) {
  125. if ($routeDocumentationChanged) {
  126. $this->warn('Discarded manual changes for route ['.implode(',', $route['methods']).'] '.$route['uri']);
  127. }
  128. } else {
  129. $this->warn('Skipping modified route ['.implode(',', $route['methods']).'] '.$route['uri']);
  130. $route['modified_output'] = $routeMatch[0];
  131. }
  132. }
  133. return $route;
  134. });
  135. });
  136. }
  137. $prependFileContents = file_exists($prependFile)
  138. ? file_get_contents($prependFile)."\n" : '';
  139. $appendFileContents = file_exists($appendFile)
  140. ? "\n".file_get_contents($appendFile) : '';
  141. $documentarian = new Documentarian();
  142. $markdown = view('apidoc::documentarian')
  143. ->with('writeCompareFile', false)
  144. ->with('frontmatter', $frontmatter)
  145. ->with('infoText', $infoText)
  146. ->with('prependMd', $prependFileContents)
  147. ->with('appendMd', $appendFileContents)
  148. ->with('outputPath', $this->option('output'))
  149. ->with('showPostmanCollectionButton', ! $this->option('noPostmanCollection'))
  150. ->with('parsedRoutes', $parsedRouteOutput);
  151. if (! is_dir($outputPath)) {
  152. $documentarian->create($outputPath);
  153. }
  154. // Write output file
  155. file_put_contents($targetFile, $markdown);
  156. // Write comparable markdown file
  157. $compareMarkdown = view('apidoc::documentarian')
  158. ->with('writeCompareFile', true)
  159. ->with('frontmatter', $frontmatter)
  160. ->with('infoText', $infoText)
  161. ->with('prependMd', $prependFileContents)
  162. ->with('appendMd', $appendFileContents)
  163. ->with('outputPath', $this->option('output'))
  164. ->with('showPostmanCollectionButton', ! $this->option('noPostmanCollection'))
  165. ->with('parsedRoutes', $parsedRouteOutput);
  166. file_put_contents($compareFile, $compareMarkdown);
  167. $this->info('Wrote index.md to: '.$outputPath);
  168. $this->info('Generating API HTML code');
  169. $documentarian->generate($outputPath);
  170. $this->info('Wrote HTML documentation to: '.$outputPath.'/index.html');
  171. if ($this->option('noPostmanCollection') !== true) {
  172. $this->info('Generating Postman collection');
  173. file_put_contents($outputPath.DIRECTORY_SEPARATOR.'collection.json', $this->generatePostmanCollection($parsedRoutes));
  174. }
  175. }
  176. /**
  177. * @return array
  178. */
  179. private function getBindings()
  180. {
  181. $bindings = $this->option('bindings');
  182. if (empty($bindings)) {
  183. return [];
  184. }
  185. $bindings = explode('|', $bindings);
  186. $resultBindings = [];
  187. foreach ($bindings as $binding) {
  188. list($name, $id) = explode(',', $binding);
  189. $resultBindings[$name] = $id;
  190. }
  191. return $resultBindings;
  192. }
  193. /**
  194. * @param $actAs
  195. */
  196. private function setUserToBeImpersonated($actAs)
  197. {
  198. if (! empty($actAs)) {
  199. if (version_compare($this->laravel->version(), '5.2.0', '<')) {
  200. $userModel = config('auth.model');
  201. $user = $userModel::find($actAs);
  202. $this->laravel['auth']->setUser($user);
  203. } else {
  204. $provider = $this->option('authProvider');
  205. $userModel = config("auth.providers.$provider.model");
  206. $user = $userModel::find($actAs);
  207. $this->laravel['auth']->guard($this->option('authGuard'))->setUser($user);
  208. }
  209. }
  210. }
  211. /**
  212. * @return mixed
  213. */
  214. private function getRoutes($routePrefix)
  215. {
  216. if ($this->option('router') === 'laravel') {
  217. return RouteFacade::getRoutes();
  218. } else {
  219. return app('Dingo\Api\Routing\Router')->getRoutes($routePrefix)->getRoutes();
  220. }
  221. }
  222. /**
  223. * @param AbstractGenerator $generator
  224. * @param $allowedRoutes
  225. * @param $routeDomain
  226. * @param $routePrefix
  227. *
  228. * @return array
  229. */
  230. private function processRoutes(AbstractGenerator $generator, array $allowedRoutes, $routeDomain, $routePrefix, $middleware)
  231. {
  232. $withResponse = $this->option('noResponseCalls') == false;
  233. $routes = $this->getRoutes($routePrefix);
  234. $bindings = $this->getBindings();
  235. $parsedRoutes = [];
  236. foreach ($routes as $route) {
  237. /** @var Route $route */
  238. if (in_array($route->getName(), $allowedRoutes)
  239. || (str_is($routeDomain, $generator->getDomain($route))
  240. && str_is($routePrefix, $generator->getUri($route)))
  241. || in_array($middleware, $route->middleware())
  242. ) {
  243. if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction()['uses'])) {
  244. $parsedRoutes[] = $generator->processRoute($route, $bindings, $this->option('header'), $withResponse && in_array('GET', $generator->getMethods($route)));
  245. $this->info('Processed route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  246. } else {
  247. $this->warn('Skipping route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  248. }
  249. }
  250. }
  251. return $parsedRoutes;
  252. }
  253. /**
  254. * @param $route
  255. *
  256. * @return bool
  257. */
  258. private function isValidRoute(Route $route)
  259. {
  260. return ! is_callable($route->getAction()['uses']) && ! is_null($route->getAction()['uses']);
  261. }
  262. /**
  263. * @param $route
  264. *
  265. * @return bool
  266. */
  267. private function isRouteVisibleForDocumentation($route)
  268. {
  269. list($class, $method) = explode('@', $route);
  270. $reflection = new ReflectionClass($class);
  271. $comment = $reflection->getMethod($method)->getDocComment();
  272. if ($comment) {
  273. $phpdoc = new DocBlock($comment);
  274. return collect($phpdoc->getTags())
  275. ->filter(function ($tag) use ($route) {
  276. return $tag->getName() === 'hideFromAPIDocumentation';
  277. })
  278. ->isEmpty();
  279. }
  280. return true;
  281. }
  282. /**
  283. * Generate Postman collection JSON file.
  284. *
  285. * @param Collection $routes
  286. *
  287. * @return string
  288. */
  289. private function generatePostmanCollection(Collection $routes)
  290. {
  291. $writer = new CollectionWriter($routes);
  292. return $writer->getCollection();
  293. }
  294. }