GenerateDocumentation.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. <?php
  2. namespace Knuckles\Scribe\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Support\Facades\URL;
  6. use Knuckles\Camel\Camel;
  7. use Knuckles\Camel\Output\OutputEndpointData;
  8. use Knuckles\Scribe\GroupedEndpoints\GroupedEndpointsFactory;
  9. use Knuckles\Scribe\Matching\RouteMatcherInterface;
  10. use Knuckles\Scribe\Tools\ConsoleOutputUtils as c;
  11. use Knuckles\Scribe\Tools\DocumentationConfig;
  12. use Knuckles\Scribe\Tools\Globals;
  13. use Knuckles\Scribe\Writing\Writer;
  14. use Shalvah\Upgrader\Upgrader;
  15. class GenerateDocumentation extends Command
  16. {
  17. protected $signature = "scribe:generate
  18. {--force : Discard any changes you've made to the YAML or Markdown files}
  19. {--no-extraction : Skip extraction of route and API info and just transform the YAML and Markdown files into HTML}
  20. ";
  21. protected $description = 'Generate API documentation from your Laravel/Dingo routes.';
  22. private DocumentationConfig $docConfig;
  23. private bool $shouldExtract;
  24. private bool $forcing;
  25. public function newLine($count = 1)
  26. {
  27. // TODO Remove when Laravel g is no longer supported
  28. $this->getOutput()->write(str_repeat("\n", $count));
  29. }
  30. public function handle(RouteMatcherInterface $routeMatcher, GroupedEndpointsFactory $groupedEndpointsFactory): void
  31. {
  32. $this->bootstrap();
  33. $groupedEndpointsInstance = $groupedEndpointsFactory->make($this, $routeMatcher);
  34. $groupedEndpoints = $this->mergeUserDefinedEndpoints(
  35. $groupedEndpointsInstance->get(),
  36. Camel::loadUserDefinedEndpoints(Camel::$camelDir)
  37. );
  38. $writer = new Writer($this->docConfig);
  39. $writer->writeDocs($groupedEndpoints);
  40. if ($groupedEndpointsInstance->hasEncounteredErrors()) {
  41. c::warn('Generated docs, but encountered some errors while processing routes.');
  42. c::warn('Check the output above for details.');
  43. }
  44. $this->upgradeConfigFileIfNeeded();
  45. }
  46. public function isForcing(): bool
  47. {
  48. return $this->forcing;
  49. }
  50. public function shouldExtract(): bool
  51. {
  52. return $this->shouldExtract;
  53. }
  54. public function getDocConfig(): DocumentationConfig
  55. {
  56. return $this->docConfig;
  57. }
  58. public function bootstrap(): void
  59. {
  60. // The --verbose option is included with all Artisan commands.
  61. Globals::$shouldBeVerbose = $this->option('verbose');
  62. c::bootstrapOutput($this->output);
  63. $this->docConfig = new DocumentationConfig(config('scribe'));
  64. // Force root URL so it works in Postman collection
  65. $baseUrl = $this->docConfig->get('base_url') ?? config('app.url');
  66. URL::forceRootUrl($baseUrl);
  67. $this->forcing = $this->option('force');
  68. $this->shouldExtract = !$this->option('no-extraction');
  69. if ($this->forcing && !$this->shouldExtract) {
  70. throw new \Exception("Can't use --force and --no-extraction together.");
  71. }
  72. // Reset this map (useful for tests)
  73. Camel::$groupFileNames = [];
  74. }
  75. protected function mergeUserDefinedEndpoints(array $groupedEndpoints, array $userDefinedEndpoints): array
  76. {
  77. foreach ($userDefinedEndpoints as $endpoint) {
  78. $existingGroupKey = Arr::first(array_keys($groupedEndpoints), function ($key) use ($groupedEndpoints, $endpoint) {
  79. $group = $groupedEndpoints[$key];
  80. return $group['name'] === ($endpoint['metadata']['groupName'] ?? $this->docConfig->get('default_group', ''));
  81. });
  82. if ($existingGroupKey !== null) {
  83. $groupedEndpoints[$existingGroupKey]['endpoints'][] = OutputEndpointData::fromExtractedEndpointArray($endpoint);
  84. } else {
  85. $groupedEndpoints[] = [
  86. 'name' => $endpoint['metadata']['groupName'] ?? $this->docConfig->get('default_group', ''),
  87. 'description' => $endpoint['metadata']['groupDescription'] ?? null,
  88. 'endpoints' => [OutputEndpointData::fromExtractedEndpointArray($endpoint)],
  89. ];
  90. }
  91. }
  92. return $groupedEndpoints;
  93. }
  94. protected function upgradeConfigFileIfNeeded(): void
  95. {
  96. $upgrader = Upgrader::ofConfigFile('config/scribe.php', __DIR__ . '/../../config/scribe.php')
  97. ->dontTouch('routes','example_languages', 'database_connections_to_transact', 'strategies');
  98. $changes = $upgrader->dryRun();
  99. if (!empty($changes)) {
  100. $this->newLine();
  101. $this->warn("You're using an updated version of Scribe, which added new items to the config file.");
  102. $this->info("Here are the changes:");
  103. foreach ($changes as $change) {
  104. $this->info($change["description"]);
  105. }
  106. if (!$this->input->isInteractive()) {
  107. $this->info("Run `php artisan scribe:upgrade` from an interactive terminal to update your config file automatically.");
  108. $this->info(sprintf("Or see the full changelog at: https://github.com/knuckleswtf/scribe/blob/%s/CHANGELOG.md,", Globals::SCRIBE_VERSION));
  109. return;
  110. }
  111. if ($this->confirm("Let's help you update your config file. Accept changes?")) {
  112. $upgrader->upgrade();
  113. $this->info(sprintf("✔ Updated. See the full changelog: https://github.com/knuckleswtf/scribe/blob/%s/CHANGELOG.md", Globals::SCRIBE_VERSION));
  114. }
  115. }
  116. }
  117. }