GenerateDocumentation.php 10 KB

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