GenerateDocumentation.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. <?php
  2. namespace Mpociot\ApiDoc\Commands;
  3. use ReflectionClass;
  4. use ReflectionException;
  5. use Illuminate\Routing\Route;
  6. use Illuminate\Console\Command;
  7. use Mpociot\ApiDoc\Tools\Flags;
  8. use Mpociot\ApiDoc\Tools\Utils;
  9. use Mpociot\Reflection\DocBlock;
  10. use Illuminate\Support\Collection;
  11. use Illuminate\Support\Facades\URL;
  12. use Mpociot\ApiDoc\Tools\Generator;
  13. use Mpociot\ApiDoc\Tools\RouteMatcher;
  14. use Mpociot\Documentarian\Documentarian;
  15. use Mpociot\ApiDoc\Postman\CollectionWriter;
  16. use Mpociot\ApiDoc\Tools\DocumentationConfig;
  17. class GenerateDocumentation extends Command
  18. {
  19. /**
  20. * The name and signature of the console command.
  21. *
  22. * @var string
  23. */
  24. protected $signature = 'apidoc:generate
  25. {--force : Force rewriting of existing routes}
  26. ';
  27. /**
  28. * The console command description.
  29. *
  30. * @var string
  31. */
  32. protected $description = 'Generate your API documentation from existing Laravel routes.';
  33. private $routeMatcher;
  34. /**
  35. * @var DocumentationConfig
  36. */
  37. private $docConfig;
  38. /**
  39. * @var string
  40. */
  41. private $baseUrl;
  42. public function __construct(RouteMatcher $routeMatcher)
  43. {
  44. parent::__construct();
  45. $this->routeMatcher = $routeMatcher;
  46. }
  47. /**
  48. * Execute the console command.
  49. *
  50. * @return void
  51. */
  52. public function handle()
  53. {
  54. // Using a global static variable here, so fuck off if you don't like it.
  55. // Also, the --verbose option is included with all Artisan commands.
  56. Flags::$shouldBeVerbose = $this->option('verbose');
  57. $this->docConfig = new DocumentationConfig(config('apidoc'));
  58. $this->baseUrl = $this->docConfig->get('base_url') ?? config('app.url');
  59. try {
  60. URL::forceRootUrl($this->baseUrl);
  61. } catch (\Error $e) {
  62. echo "Warning: Couldn't force base url as your version of Lumen doesn't have the forceRootUrl method.\n";
  63. echo "You should probably double check URLs in your generated documentation.\n";
  64. }
  65. $usingDingoRouter = strtolower($this->docConfig->get('router')) == 'dingo';
  66. $routes = $this->docConfig->get('routes');
  67. $routes = $usingDingoRouter
  68. ? $this->routeMatcher->getDingoRoutesToBeDocumented($routes)
  69. : $this->routeMatcher->getLaravelRoutesToBeDocumented($routes);
  70. $generator = new Generator($this->docConfig);
  71. $parsedRoutes = $this->processRoutes($generator, $routes);
  72. $groupedRoutes = collect($parsedRoutes)
  73. ->groupBy('groupName')
  74. ->sortBy(static function ($group) {
  75. /* @var $group Collection */
  76. return $group->first()['groupName'];
  77. }, SORT_NATURAL);
  78. $this->writeMarkdown($groupedRoutes);
  79. }
  80. /**
  81. * @param Collection $parsedRoutes
  82. *
  83. * @return void
  84. */
  85. private function writeMarkdown($parsedRoutes)
  86. {
  87. $outputPath = $this->docConfig->get('output');
  88. $targetFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'index.md';
  89. $compareFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'.compare.md';
  90. $prependFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'prepend.md';
  91. $appendFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'append.md';
  92. $infoText = view('apidoc::partials.info')
  93. ->with('outputPath', ltrim($outputPath, 'public/'))
  94. ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection());
  95. $settings = ['languages' => $this->docConfig->get('example_languages')];
  96. $parsedRouteOutput = $parsedRoutes->map(function ($routeGroup) use ($settings) {
  97. return $routeGroup->map(function ($route) use ($settings) {
  98. if (count($route['cleanBodyParameters']) && ! isset($route['headers']['Content-Type'])) {
  99. // Set content type if the user forgot to set it
  100. $route['headers']['Content-Type'] = 'application/json';
  101. }
  102. $route['output'] = (string) view('apidoc::partials.route')
  103. ->with('route', $route)
  104. ->with('settings', $settings)
  105. ->with('baseUrl', $this->baseUrl)
  106. ->render();
  107. return $route;
  108. });
  109. });
  110. $frontmatter = view('apidoc::partials.frontmatter')
  111. ->with('settings', $settings);
  112. /*
  113. * In case the target file already exists, we should check if the documentation was modified
  114. * and skip the modified parts of the routes.
  115. */
  116. if (file_exists($targetFile) && file_exists($compareFile)) {
  117. $generatedDocumentation = file_get_contents($targetFile);
  118. $compareDocumentation = file_get_contents($compareFile);
  119. if (preg_match('/---(.*)---\\s<!-- START_INFO -->/is', $generatedDocumentation, $generatedFrontmatter)) {
  120. $frontmatter = trim($generatedFrontmatter[1], "\n");
  121. }
  122. $parsedRouteOutput->transform(function ($routeGroup) use ($generatedDocumentation, $compareDocumentation) {
  123. return $routeGroup->transform(function ($route) use ($generatedDocumentation, $compareDocumentation) {
  124. if (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $generatedDocumentation, $existingRouteDoc)) {
  125. $routeDocumentationChanged = (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $compareDocumentation, $lastDocWeGeneratedForThisRoute) && $lastDocWeGeneratedForThisRoute[1] !== $existingRouteDoc[1]);
  126. if ($routeDocumentationChanged === false || $this->option('force')) {
  127. if ($routeDocumentationChanged) {
  128. $this->warn('Discarded manual changes for route ['.implode(',', $route['methods']).'] '.$route['uri']);
  129. }
  130. } else {
  131. $this->warn('Skipping modified route ['.implode(',', $route['methods']).'] '.$route['uri']);
  132. $route['modified_output'] = $existingRouteDoc[0];
  133. }
  134. }
  135. return $route;
  136. });
  137. });
  138. }
  139. $prependFileContents = file_exists($prependFile)
  140. ? file_get_contents($prependFile)."\n" : '';
  141. $appendFileContents = file_exists($appendFile)
  142. ? "\n".file_get_contents($appendFile) : '';
  143. $documentarian = new Documentarian();
  144. $markdown = view('apidoc::documentarian')
  145. ->with('writeCompareFile', false)
  146. ->with('frontmatter', $frontmatter)
  147. ->with('infoText', $infoText)
  148. ->with('prependMd', $prependFileContents)
  149. ->with('appendMd', $appendFileContents)
  150. ->with('outputPath', $this->docConfig->get('output'))
  151. ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection())
  152. ->with('parsedRoutes', $parsedRouteOutput);
  153. if (! is_dir($outputPath)) {
  154. $documentarian->create($outputPath);
  155. }
  156. // Write output file
  157. file_put_contents($targetFile, $markdown);
  158. // Write comparable markdown file
  159. $compareMarkdown = view('apidoc::documentarian')
  160. ->with('writeCompareFile', true)
  161. ->with('frontmatter', $frontmatter)
  162. ->with('infoText', $infoText)
  163. ->with('prependMd', $prependFileContents)
  164. ->with('appendMd', $appendFileContents)
  165. ->with('outputPath', $this->docConfig->get('output'))
  166. ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection())
  167. ->with('parsedRoutes', $parsedRouteOutput);
  168. file_put_contents($compareFile, $compareMarkdown);
  169. $this->info('Wrote index.md to: '.$outputPath);
  170. $this->info('Generating API HTML code');
  171. $documentarian->generate($outputPath);
  172. $this->info('Wrote HTML documentation to: '.$outputPath.'/index.html');
  173. if ($this->shouldGeneratePostmanCollection()) {
  174. $this->info('Generating Postman collection');
  175. file_put_contents($outputPath.DIRECTORY_SEPARATOR.'collection.json', $this->generatePostmanCollection($parsedRoutes));
  176. }
  177. if ($logo = $this->docConfig->get('logo')) {
  178. copy(
  179. $logo,
  180. $outputPath.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'logo.png'
  181. );
  182. }
  183. }
  184. /**
  185. * @param Generator $generator
  186. * @param array $routes
  187. *
  188. * @return array
  189. */
  190. private function processRoutes(Generator $generator, array $routes)
  191. {
  192. $parsedRoutes = [];
  193. foreach ($routes as $routeItem) {
  194. $route = $routeItem['route'];
  195. /** @var Route $route */
  196. if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction())) {
  197. $parsedRoutes[] = $generator->processRoute($route, $routeItem['apply'] ?? []);
  198. $this->info('Processed route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  199. } else {
  200. $this->warn('Skipping route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  201. }
  202. }
  203. return $parsedRoutes;
  204. }
  205. /**
  206. * @param Route $route
  207. *
  208. * @return bool
  209. */
  210. private function isValidRoute(Route $route)
  211. {
  212. $action = Utils::getRouteClassAndMethodNames($route->getAction());
  213. if (is_array($action)) {
  214. $action = implode('@', $action);
  215. }
  216. return ! is_callable($action) && ! is_null($action);
  217. }
  218. /**
  219. * @param array $action
  220. *
  221. * @throws ReflectionException
  222. *
  223. * @return bool
  224. */
  225. private function isRouteVisibleForDocumentation(array $action)
  226. {
  227. list($class, $method) = Utils::getRouteClassAndMethodNames($action);
  228. $reflection = new ReflectionClass($class);
  229. if (! $reflection->hasMethod($method)) {
  230. return false;
  231. }
  232. $comment = $reflection->getMethod($method)->getDocComment();
  233. if ($comment) {
  234. $phpdoc = new DocBlock($comment);
  235. return collect($phpdoc->getTags())
  236. ->filter(function ($tag) {
  237. return $tag->getName() === 'hideFromAPIDocumentation';
  238. })
  239. ->isEmpty();
  240. }
  241. return true;
  242. }
  243. /**
  244. * Generate Postman collection JSON file.
  245. *
  246. * @param Collection $routes
  247. *
  248. * @return string
  249. */
  250. private function generatePostmanCollection(Collection $routes)
  251. {
  252. $writer = new CollectionWriter($routes, $this->baseUrl);
  253. return $writer->getCollection();
  254. }
  255. /**
  256. * Checks config if it should generate Postman collection.
  257. *
  258. * @return bool
  259. */
  260. private function shouldGeneratePostmanCollection()
  261. {
  262. return $this->docConfig->get('postman.enabled', is_bool($this->docConfig->get('postman')) ? $this->docConfig->get('postman') : false);
  263. }
  264. }