GenerateDocumentation.php 8.8 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. $routes = config('apidoc.router') == 'dingo'
  44. ? $this->routeMatcher->getDingoRoutesToBeDocumented(config('apidoc.routes'))
  45. : $this->routeMatcher->getLaravelRoutesToBeDocumented(config('apidoc.routes'));
  46. if ($this->option('router') === 'laravel') {
  47. $generator = new LaravelGenerator();
  48. } else {
  49. $generator = new DingoGenerator();
  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 = $this->option('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', ! $this->option('noPostmanCollection'));
  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, $routeMatch)) {
  93. $routeDocumentationChanged = (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $compareDocumentation, $compareMatch) && $compareMatch[1] !== $routeMatch[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'] = $routeMatch[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', $this->option('output'))
  119. ->with('showPostmanCollectionButton', ! $this->option('noPostmanCollection'))
  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', $this->option('output'))
  134. ->with('showPostmanCollectionButton', ! $this->option('noPostmanCollection'))
  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 ($this->option('noPostmanCollection') !== true) {
  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 ['route' => $route, 'apply' => $apply]) {
  156. /** @var Route $route */
  157. if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction()['uses'])) {
  158. $parsedRoutes[] = $generator->processRoute($route, $apply);
  159. $this->info('Processed route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  160. } else {
  161. $this->warn('Skipping route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
  162. }
  163. }
  164. return $parsedRoutes;
  165. }
  166. /**
  167. * @param $route
  168. *
  169. * @return bool
  170. */
  171. private function isValidRoute(Route $route)
  172. {
  173. return ! is_callable($route->getAction()['uses']) && ! is_null($route->getAction()['uses']);
  174. }
  175. /**
  176. * @param $route
  177. *
  178. * @return bool
  179. */
  180. private function isRouteVisibleForDocumentation($route)
  181. {
  182. list($class, $method) = explode('@', $route);
  183. $reflection = new ReflectionClass($class);
  184. $comment = $reflection->getMethod($method)->getDocComment();
  185. if ($comment) {
  186. $phpdoc = new DocBlock($comment);
  187. return collect($phpdoc->getTags())
  188. ->filter(function ($tag) use ($route) {
  189. return $tag->getName() === 'hideFromAPIDocumentation';
  190. })
  191. ->isEmpty();
  192. }
  193. return true;
  194. }
  195. /**
  196. * Generate Postman collection JSON file.
  197. *
  198. * @param Collection $routes
  199. *
  200. * @return string
  201. */
  202. private function generatePostmanCollection(Collection $routes)
  203. {
  204. $writer = new CollectionWriter($routes);
  205. return $writer->getCollection();
  206. }
  207. }