GenerateDocumentation.php 8.9 KB

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