GenerateDocumentation.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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\ApiDoc\Tools\RouteMatcher;
  9. use Mpociot\ApiDoc\Generators\Generator;
  10. use Mpociot\Documentarian\Documentarian;
  11. use Mpociot\ApiDoc\Postman\CollectionWriter;
  12. class GenerateDocumentation extends Command
  13. {
  14. /**
  15. * The name and signature of the console command.
  16. *
  17. * @var string
  18. */
  19. protected $signature = 'apidoc:generate
  20. {--force : Force rewriting of existing routes}
  21. ';
  22. /**
  23. * The console command description.
  24. *
  25. * @var string
  26. */
  27. protected $description = 'Generate your API documentation from existing Laravel routes.';
  28. private $routeMatcher;
  29. public function __construct(RouteMatcher $routeMatcher)
  30. {
  31. parent::__construct();
  32. $this->routeMatcher = $routeMatcher;
  33. }
  34. /**
  35. * Execute the console command.
  36. *
  37. * @return false|null
  38. */
  39. public function handle()
  40. {
  41. $usingDingoRouter = config('apidoc.router') == 'dingo';
  42. if ($usingDingoRouter) {
  43. $routes = $this->routeMatcher->getDingoRoutesToBeDocumented(config('apidoc.routes'));
  44. } else {
  45. $routes = $this->routeMatcher->getLaravelRoutesToBeDocumented(config('apidoc.routes'));
  46. }
  47. $generator = new Generator();
  48. $parsedRoutes = $this->processRoutes($generator, $routes);
  49. $parsedRoutes = collect($parsedRoutes)->groupBy('group')
  50. ->sort(function ($a, $b) {
  51. return strcmp($a->first()['group'], $b->first()['group']);
  52. });
  53. $this->writeMarkdown($parsedRoutes);
  54. }
  55. /**
  56. * @param Collection $parsedRoutes
  57. *
  58. * @return void
  59. */
  60. private function writeMarkdown($parsedRoutes)
  61. {
  62. $outputPath = config('apidoc.output');
  63. $targetFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'index.md';
  64. $compareFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'.compare.md';
  65. $prependFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'prepend.md';
  66. $appendFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'append.md';
  67. $infoText = view('apidoc::partials.info')
  68. ->with('outputPath', ltrim($outputPath, 'public/'))
  69. ->with('showPostmanCollectionButton', config('apidoc.postman'));
  70. $parsedRouteOutput = $parsedRoutes->map(function ($routeGroup) {
  71. return $routeGroup->map(function ($route) {
  72. $route['output'] = (string) view('apidoc::partials.route')->with('route', $route)->render();
  73. return $route;
  74. });
  75. });
  76. $frontmatter = view('apidoc::partials.frontmatter');
  77. /*
  78. * In case the target file already exists, we should check if the documentation was modified
  79. * and skip the modified parts of the routes.
  80. */
  81. if (file_exists($targetFile) && file_exists($compareFile)) {
  82. $generatedDocumentation = file_get_contents($targetFile);
  83. $compareDocumentation = file_get_contents($compareFile);
  84. if (preg_match('/---(.*)---\\s<!-- START_INFO -->/is', $generatedDocumentation, $generatedFrontmatter)) {
  85. $frontmatter = trim($generatedFrontmatter[1], "\n");
  86. }
  87. $parsedRouteOutput->transform(function ($routeGroup) use ($generatedDocumentation, $compareDocumentation) {
  88. return $routeGroup->transform(function ($route) use ($generatedDocumentation, $compareDocumentation) {
  89. if (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $generatedDocumentation, $existingRouteDoc)) {
  90. $routeDocumentationChanged = (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $compareDocumentation, $lastDocWeGeneratedForThisRoute) && $lastDocWeGeneratedForThisRoute[1] !== $existingRouteDoc[1]);
  91. if ($routeDocumentationChanged === false || $this->option('force')) {
  92. if ($routeDocumentationChanged) {
  93. $this->warn('Discarded manual changes for route ['.implode(',', $route['methods']).'] '.$route['uri']);
  94. }
  95. } else {
  96. $this->warn('Skipping modified route ['.implode(',', $route['methods']).'] '.$route['uri']);
  97. $route['modified_output'] = $existingRouteDoc[0];
  98. }
  99. }
  100. return $route;
  101. });
  102. });
  103. }
  104. $prependFileContents = file_exists($prependFile)
  105. ? file_get_contents($prependFile)."\n" : '';
  106. $appendFileContents = file_exists($appendFile)
  107. ? "\n".file_get_contents($appendFile) : '';
  108. $documentarian = new Documentarian();
  109. $markdown = view('apidoc::documentarian')
  110. ->with('writeCompareFile', false)
  111. ->with('frontmatter', $frontmatter)
  112. ->with('infoText', $infoText)
  113. ->with('prependMd', $prependFileContents)
  114. ->with('appendMd', $appendFileContents)
  115. ->with('outputPath', config('apidoc.output'))
  116. ->with('showPostmanCollectionButton', config('apidoc.postman'))
  117. ->with('parsedRoutes', $parsedRouteOutput);
  118. if (! is_dir($outputPath)) {
  119. $documentarian->create($outputPath);
  120. }
  121. // Write output file
  122. file_put_contents($targetFile, $markdown);
  123. // Write comparable markdown file
  124. $compareMarkdown = view('apidoc::documentarian')
  125. ->with('writeCompareFile', true)
  126. ->with('frontmatter', $frontmatter)
  127. ->with('infoText', $infoText)
  128. ->with('prependMd', $prependFileContents)
  129. ->with('appendMd', $appendFileContents)
  130. ->with('outputPath', config('apidoc.output'))
  131. ->with('showPostmanCollectionButton', config('apidoc.postman'))
  132. ->with('parsedRoutes', $parsedRouteOutput);
  133. file_put_contents($compareFile, $compareMarkdown);
  134. $this->info('Wrote index.md to: '.$outputPath);
  135. $this->info('Generating API HTML code');
  136. $documentarian->generate($outputPath);
  137. $this->info('Wrote HTML documentation to: '.$outputPath.'/index.html');
  138. if (config('apidoc.postman')) {
  139. $this->info('Generating Postman collection');
  140. file_put_contents($outputPath.DIRECTORY_SEPARATOR.'collection.json', $this->generatePostmanCollection($parsedRoutes));
  141. }
  142. }
  143. /**
  144. * @param Generator $generator
  145. * @param array $routes
  146. *
  147. * @return array
  148. */
  149. private function processRoutes(Generator $generator, array $routes)
  150. {
  151. $parsedRoutes = [];
  152. foreach ($routes as $routeItem) {
  153. $route = $routeItem['route'];
  154. /** @var Route $route */
  155. if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction()['uses'])) {
  156. $parsedRoutes[] = $generator->processRoute($route, $routeItem['apply']);
  157. $this->info('Processed route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  158. } else {
  159. $this->warn('Skipping route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  160. }
  161. }
  162. return $parsedRoutes;
  163. }
  164. /**
  165. * @param $route
  166. *
  167. * @return bool
  168. */
  169. private function isValidRoute(Route $route)
  170. {
  171. return ! is_callable($route->getAction()['uses']) && ! is_null($route->getAction()['uses']);
  172. }
  173. /**
  174. * @param $route
  175. *
  176. * @return bool
  177. */
  178. private function isRouteVisibleForDocumentation($route)
  179. {
  180. list($class, $method) = explode('@', $route);
  181. $reflection = new ReflectionClass($class);
  182. $comment = $reflection->getMethod($method)->getDocComment();
  183. if ($comment) {
  184. $phpdoc = new DocBlock($comment);
  185. return collect($phpdoc->getTags())
  186. ->filter(function ($tag) use ($route) {
  187. return $tag->getName() === 'hideFromAPIDocumentation';
  188. })
  189. ->isEmpty();
  190. }
  191. return true;
  192. }
  193. /**
  194. * Generate Postman collection JSON file.
  195. *
  196. * @param Collection $routes
  197. *
  198. * @return string
  199. */
  200. private function generatePostmanCollection(Collection $routes)
  201. {
  202. $writer = new CollectionWriter($routes);
  203. return $writer->getCollection();
  204. }
  205. }