Writer.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. namespace Knuckles\Scribe\Writing;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Arr;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Support\Facades\Storage;
  7. use Illuminate\Support\Str;
  8. use Knuckles\Pastel\Pastel;
  9. use Knuckles\Scribe\Tools\DocumentationConfig;
  10. use Knuckles\Scribe\Tools\Flags;
  11. use Shalvah\Clara\Clara;
  12. class Writer
  13. {
  14. /**
  15. * @var Clara
  16. */
  17. protected $clara;
  18. /**
  19. * @var DocumentationConfig
  20. */
  21. private $config;
  22. /**
  23. * @var string
  24. */
  25. private $baseUrl;
  26. /**
  27. * @var bool
  28. */
  29. private $forceIt;
  30. /**
  31. * @var bool
  32. */
  33. private $shouldGeneratePostmanCollection = true;
  34. /**
  35. * @var Pastel
  36. */
  37. private $pastel;
  38. /**
  39. * @var bool
  40. */
  41. private $isStatic;
  42. /**
  43. * @var string
  44. */
  45. private $sourceOutputPath;
  46. /**
  47. * @var string
  48. */
  49. private $outputPath;
  50. /**
  51. * @var string
  52. */
  53. private $fileModificationTimesFile;
  54. /**
  55. * @var array
  56. */
  57. private $lastTimesWeModifiedTheseFiles;
  58. public function __construct(DocumentationConfig $config = null, bool $forceIt = false, $clara = null)
  59. {
  60. // If no config is injected, pull from global
  61. $this->config = $config ?: new DocumentationConfig(config('scribe'));
  62. $this->baseUrl = $this->config->get('base_url') ?? config('app.url');
  63. $this->forceIt = $forceIt;
  64. $this->clara = $clara ?: clara('knuckleswtf/scribe', Flags::$shouldBeVerbose)->only();
  65. $this->shouldGeneratePostmanCollection = $this->config->get('postman.enabled', false);
  66. $this->pastel = new Pastel();
  67. $this->isStatic = $this->config->get('type') === 'static';
  68. $this->sourceOutputPath = 'resources/docs';
  69. $this->outputPath = $this->isStatic ? 'public/docs' : 'resources/views/scribe';
  70. $this->fileModificationTimesFile = $this->sourceOutputPath . '/source/.filemtimes';
  71. $this->lastTimesWeModifiedTheseFiles = [];
  72. }
  73. public function writeDocs(Collection $routes)
  74. {
  75. // The source Markdown files always go in resources/docs/source.
  76. // The static assets (js/, css/, and images/) always go in public/docs/.
  77. // For 'static' docs, the output files (index.html, collection.json) go in public/docs/.
  78. // For 'laravel' docs, the output files (index.blade.php, collection.json)
  79. // go in resources/views/scribe/ and storage/app/scribe/ respectively.
  80. $this->writeMarkdownAndSourceFiles($routes);
  81. $this->writeHtmlDocs();
  82. $this->writePostmanCollection($routes);
  83. }
  84. /**
  85. * @param Collection $parsedRoutes
  86. *
  87. * @return void
  88. */
  89. public function writeMarkdownAndSourceFiles(Collection $parsedRoutes)
  90. {
  91. $settings = [
  92. 'languages' => $this->config->get('example_languages'),
  93. 'logo' => $this->config->get('logo'),
  94. 'title' => config('app.name', '') . ' API Documentation',
  95. ];
  96. $this->clara->info('Writing source Markdown files to: ' . $this->sourceOutputPath);
  97. if (!is_dir($this->sourceOutputPath . '/source')) {
  98. mkdir($this->sourceOutputPath . '/source', 0777, true);
  99. }
  100. $this->writeIndexMarkdownFile($settings);
  101. $this->writeAuthMarkdownFile();
  102. $this->writeRoutesMarkdownFile($parsedRoutes, $settings);
  103. $this->clara->info('Wrote source Markdown files to: ' . $this->sourceOutputPath);
  104. }
  105. public function generateMarkdownOutputForEachRoute(Collection $parsedRoutes, array $settings): Collection
  106. {
  107. $routesWithOutput = $parsedRoutes->map(function (Collection $routeGroup) use ($settings) {
  108. return $routeGroup->map(function (array $route) use ($settings) {
  109. if (count($route['cleanBodyParameters']) && !isset($route['headers']['Content-Type'])) {
  110. // Set content type if the user forgot to set it
  111. $route['headers']['Content-Type'] = 'application/json';
  112. }
  113. $hasRequestOptions = !empty($route['headers'])
  114. || !empty($route['cleanQueryParameters'])
  115. || !empty($route['cleanBodyParameters']);
  116. $route['output'] = (string)view('scribe::partials.route')
  117. ->with('hasRequestOptions', $hasRequestOptions)
  118. ->with('route', $route)
  119. ->with('settings', $settings)
  120. ->with('baseUrl', $this->baseUrl)
  121. ->render();
  122. return $route;
  123. });
  124. });
  125. return $routesWithOutput;
  126. }
  127. protected function writePostmanCollection(Collection $parsedRoutes): void
  128. {
  129. if ($this->shouldGeneratePostmanCollection) {
  130. $this->clara->info('Generating Postman collection');
  131. $collection = $this->generatePostmanCollection($parsedRoutes);
  132. if ($this->isStatic) {
  133. $collectionPath = "{$this->outputPath}/collection.json";
  134. file_put_contents($collectionPath, $collection);
  135. } else {
  136. Storage::disk('local')->put('scribe/collection.json', $collection);
  137. $collectionPath = 'storage/app/scribe/collection.json';
  138. }
  139. $this->clara->success("Wrote Postman collection to: {$collectionPath}");
  140. }
  141. }
  142. /**
  143. * Generate Postman collection JSON file.
  144. *
  145. * @param Collection $routes
  146. *
  147. * @return string
  148. */
  149. public function generatePostmanCollection(Collection $routes)
  150. {
  151. /** @var PostmanCollectionWriter $writer */
  152. $writer = app()->makeWith(
  153. PostmanCollectionWriter::class,
  154. ['routeGroups' => $routes, 'baseUrl' => $this->baseUrl]
  155. );
  156. return $writer->getCollection();
  157. }
  158. protected function performFinalTasksForLaravelType(): void
  159. {
  160. // Make output a Blade view
  161. if (!is_dir($this->outputPath)) {
  162. mkdir($this->outputPath);
  163. }
  164. rename("public/docs/index.html", "$this->outputPath/index.blade.php");
  165. $contents = file_get_contents("$this->outputPath/index.blade.php");
  166. // Rewrite links to go through Laravel
  167. $contents = str_replace('href="css/style.css"', 'href="/docs/css/style.css"', $contents);
  168. $contents = str_replace('src="js/all.js"', 'src="/docs/js/all.js"', $contents);
  169. $contents = str_replace('src="images/', 'src="/docs/images/', $contents);
  170. $contents = preg_replace('#href="./collection.json"#', 'href="{{ route("scribe.json") }}"', $contents);
  171. file_put_contents("$this->outputPath/index.blade.php", $contents);
  172. }
  173. public function writeHtmlDocs(): void
  174. {
  175. $this->clara->info('Generating API HTML code');
  176. $this->pastel->generate($this->sourceOutputPath . '/source/index.md', 'public/docs');
  177. if (!$this->isStatic) {
  178. $this->performFinalTasksForLaravelType();
  179. }
  180. $this->clara->success("Wrote HTML documentation to: {$this->outputPath}");
  181. }
  182. protected function writeIndexMarkdownFile(array $settings): void
  183. {
  184. $frontmatter = view('scribe::partials.frontmatter')
  185. ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection)
  186. // This path is wrong for laravel type but will be replaced in post
  187. ->with('postmanCollectionLink', './collection.json')
  188. ->with('outputPath', 'docs')
  189. ->with('settings', $settings);
  190. $indexFile = $this->sourceOutputPath . '/source/index.md';
  191. $introMarkdown = view('scribe::index')
  192. ->with('frontmatter', $frontmatter);
  193. $this->writeFile($indexFile, $introMarkdown);
  194. }
  195. protected function writeAuthMarkdownFile(): void
  196. {
  197. $isAuthed = $this->config->get('auth.enabled', false);
  198. $text = '';
  199. if ($isAuthed) {
  200. $strategy = $this->config->get('auth.in');
  201. $parameterName = $this->config->get('auth.name');
  202. $text = Arr::random([
  203. "This API is authenticated by sending ",
  204. "To authenticate requests, include ",
  205. "Authenticate requests to this API's endpoints by sending ",
  206. ]);
  207. switch ($strategy) {
  208. case 'query':
  209. $text .= "a query parameter **`$parameterName`** in the request.";
  210. break;
  211. case 'body':
  212. $text .= "a parameter **`$parameterName`** in the body of the request.";
  213. break;
  214. case 'query_or_body':
  215. $text .= "a parameter **`$parameterName`** either in the query string or in the request body.";
  216. break;
  217. case 'bearer':
  218. $text .= "an **`Authorization`** header with the value **`\"Bearer {your-token}\"`**.";
  219. break;
  220. case 'basic':
  221. $text .= "an **`Authorization`** header in the form **`\"Basic {credentials}\"`**. The value of `{credentials}` should be your username/id and your password, joined with a colon (:), and then base64-encoded.";
  222. break;
  223. case 'header':
  224. $text .= "a **`$parameterName`** header with the value **`\"{your-token}\"`**.";
  225. break;
  226. }
  227. $howToFetch = $this->config->get('auth.how_to_fetch', '');
  228. $text .= " $howToFetch";
  229. }
  230. $authMarkdown = view('scribe::authentication', ['isAuthed' => $isAuthed, 'text' => $text]);
  231. $this->writeFile($this->sourceOutputPath . '/source/authentication.md', $authMarkdown);
  232. }
  233. protected function writeRoutesMarkdownFile(Collection $parsedRoutes, array $settings): void
  234. {
  235. if (!is_dir($this->sourceOutputPath . '/source/groups')) {
  236. mkdir($this->sourceOutputPath . '/source/groups', 0777, true);
  237. }
  238. if (file_exists($this->fileModificationTimesFile)) {
  239. $this->lastTimesWeModifiedTheseFiles = explode("\n", file_get_contents($this->fileModificationTimesFile));
  240. array_shift($this->lastTimesWeModifiedTheseFiles);
  241. array_shift($this->lastTimesWeModifiedTheseFiles);
  242. $this->lastTimesWeModifiedTheseFiles = collect($this->lastTimesWeModifiedTheseFiles)
  243. ->mapWithKeys(function ($line) {
  244. [$filePath, $mtime] = explode("=", $line);
  245. return [$filePath => $mtime];
  246. })->toArray();
  247. }
  248. // Generate Markdown for each route. Not using a Blade component bc of some complex logic
  249. $parsedRoutesWithOutput = $this->generateMarkdownOutputForEachRoute($parsedRoutes, $settings);
  250. $parsedRoutesWithOutput->each(function ($routesInGroup, $groupName) use (
  251. $parsedRoutesWithOutput
  252. ) {
  253. static $counter = 0;
  254. $groupId = "$counter-" . Str::slug($groupName);
  255. $routeGroupMarkdownFile = $this->sourceOutputPath . "/source/groups/$groupId.md";
  256. $counter++;
  257. if ($this->hasFileBeenModified($routeGroupMarkdownFile)) {
  258. if ($this->forceIt) {
  259. $this->clara->warn("Discarded manual changes for file $routeGroupMarkdownFile");
  260. } else {
  261. $this->clara->warn("Skipping modified file $routeGroupMarkdownFile");
  262. return;
  263. }
  264. }
  265. $groupDescription = Arr::first($routesInGroup, function ($route) {
  266. return $route['metadata']['groupDescription'] !== '';
  267. })['metadata']['groupDescription'] ?? '';
  268. $groupMarkdown = view('scribe::partials.group')
  269. ->with('groupName', $groupName)
  270. ->with('groupDescription', $groupDescription)
  271. ->with('routes', $routesInGroup);
  272. $this->writeFile($routeGroupMarkdownFile, $groupMarkdown);
  273. });
  274. $this->writeModificationTimesFile();
  275. }
  276. /**
  277. */
  278. protected function writeFile(string $filePath, $markdown): void
  279. {
  280. file_put_contents($filePath, $markdown);
  281. $this->lastTimesWeModifiedTheseFiles[$filePath] = time();
  282. }
  283. /**
  284. */
  285. protected function writeModificationTimesFile(): void
  286. {
  287. $content = "# GENERATED. YOU SHOULDN'T MODIFY OR DELETE THIS FILE.\n";
  288. $content .= "# Scribe uses this file to know when you change something manually in your docs.\n";
  289. $content .= collect($this->lastTimesWeModifiedTheseFiles)
  290. ->map(function ($mtime, $filePath) {
  291. return "$filePath=$mtime";
  292. })->implode("\n");
  293. file_put_contents($this->fileModificationTimesFile, $content);
  294. }
  295. /**
  296. */
  297. protected function hasFileBeenModified(string $filePath): bool
  298. {
  299. $oldFileModificationTime = $this->lastTimesWeModifiedTheseFiles[$filePath] ?? null;
  300. if ($oldFileModificationTime) {
  301. $latestFileModifiedTime = filemtime($filePath);
  302. $wasFileModifiedManually = $latestFileModifiedTime > (int)$oldFileModificationTime;
  303. return $wasFileModifiedManually;
  304. }
  305. return false;
  306. }
  307. }