GenerateDocumentation.php 11 KB

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