Writer.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. namespace Knuckles\Scribe\Writing;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\Storage;
  6. use Illuminate\Support\Str;
  7. use Knuckles\Pastel\Pastel;
  8. use Knuckles\Scribe\Tools\ConsoleOutputUtils;
  9. use Knuckles\Scribe\Tools\DocumentationConfig;
  10. use Knuckles\Scribe\Tools\Globals;
  11. use Knuckles\Scribe\Tools\Utils;
  12. use Symfony\Component\Yaml\Yaml;
  13. class Writer
  14. {
  15. /**
  16. * @var DocumentationConfig
  17. */
  18. private $config;
  19. /**
  20. * @var string
  21. */
  22. private $baseUrl;
  23. /**
  24. * @var bool
  25. */
  26. private $shouldOverwrite;
  27. /**
  28. * @var bool
  29. */
  30. private $shouldGeneratePostmanCollection = false;
  31. /**
  32. * @var bool
  33. */
  34. private $shouldGenerateOpenAPISpec = false;
  35. /**
  36. * @var Pastel
  37. */
  38. private $pastel;
  39. /**
  40. * @var bool
  41. */
  42. private $isStatic;
  43. /**
  44. * @var string
  45. */
  46. private $sourceOutputPath = 'resources/docs';
  47. /**
  48. * @var string
  49. */
  50. private $staticTypeOutputPath;
  51. /**
  52. * @var string
  53. */
  54. private $laravelTypeOutputPath = 'resources/views/scribe';
  55. /**
  56. * @var string
  57. */
  58. private $fileModificationTimesFile;
  59. /**
  60. * @var array
  61. */
  62. private $lastTimesWeModifiedTheseFiles = [];
  63. public function __construct(DocumentationConfig $config = null, bool $shouldOverwrite = false)
  64. {
  65. // If no config is injected, pull from global. Makes testing easier.
  66. $this->config = $config ?: new DocumentationConfig(config('scribe'));
  67. $this->baseUrl = $this->config->get('base_url') ?? config('app.url');
  68. $this->shouldOverwrite = $shouldOverwrite;
  69. $this->shouldGeneratePostmanCollection = $this->config->get('postman.enabled', false);
  70. $this->shouldGenerateOpenAPISpec = $this->config->get('openapi.enabled', false);
  71. $this->pastel = new Pastel();
  72. $this->isStatic = $this->config->get('type') === 'static';
  73. $this->staticTypeOutputPath = rtrim($this->config->get('static.output_path', 'public/docs'), '/');
  74. $this->fileModificationTimesFile = $this->sourceOutputPath . '/.filemtimes';
  75. $this->lastTimesWeModifiedTheseFiles = [];
  76. }
  77. public function writeDocs(Collection $routes = null)
  78. {
  79. // The source Markdown files always go in resources/docs.
  80. // The static assets (js/, css/, and images/) always go in public/docs/.
  81. // For 'static' docs, the output files (index.html, collection.json) go in public/docs/.
  82. // For 'laravel' docs, the output files (index.blade.php, collection.json)
  83. // go in resources/views/scribe/ and storage/app/scribe/ respectively.
  84. // When running with --no-extraction, $routes will be null.
  85. // In that case, we only want to write HTMl docs again, hence the conditionals below
  86. $routes && $this->writeMarkdownAndSourceFiles($routes);
  87. $this->writeHtmlDocs();
  88. $routes && $this->writePostmanCollection($routes);
  89. $routes && $this->writeOpenAPISpec($routes);
  90. }
  91. /**
  92. * @param Collection $parsedRoutes
  93. *
  94. * @return void
  95. */
  96. public function writeMarkdownAndSourceFiles(Collection $parsedRoutes)
  97. {
  98. $settings = [
  99. 'languages' => $this->config->get('example_languages'),
  100. 'logo' => $this->config->get('logo'),
  101. 'title' => $this->config->get('title') ?: config('app.name', '') . ' Documentation',
  102. 'auth' => $this->config->get('auth'),
  103. 'interactive' => $this->config->get('interactive', true)
  104. ];
  105. ConsoleOutputUtils::info('Writing source Markdown files to: ' . $this->sourceOutputPath);
  106. if (!is_dir($this->sourceOutputPath)) {
  107. mkdir($this->sourceOutputPath, 0777, true);
  108. }
  109. $this->fetchLastTimeWeModifiedFilesFromTrackingFile();
  110. $this->writeEndpointsMarkdownFile($parsedRoutes, $settings);
  111. $this->writeIndexMarkdownFile($settings);
  112. $this->writeAuthMarkdownFile();
  113. $this->writeModificationTimesTrackingFile();
  114. ConsoleOutputUtils::info('Wrote source Markdown files to: ' . $this->sourceOutputPath);
  115. }
  116. public function generateMarkdownOutputForEachRoute(Collection $parsedRoutes, array $settings): Collection
  117. {
  118. $routesWithOutput = $parsedRoutes->map(function (Collection $routeGroup) use ($settings) {
  119. return $routeGroup->map(function (array $route) use ($settings) {
  120. $hasRequestOptions = !empty($route['headers'])
  121. || !empty($route['cleanQueryParameters'])
  122. || !empty($route['cleanBodyParameters']);
  123. // Needed for Try It Out
  124. $auth = $settings['auth'];
  125. if ($auth['in'] === 'bearer' || $auth['in'] === 'basic') {
  126. $auth['name'] = 'Authorization';
  127. $auth['location'] = 'header';
  128. $auth['prefix'] = ucfirst($auth['in']).' ';
  129. } else {
  130. $auth['location'] = $auth['in'];
  131. $auth['prefix'] = '';
  132. }
  133. $route['output'] = (string)view('scribe::partials.endpoint')
  134. ->with('hasRequestOptions', $hasRequestOptions)
  135. ->with('route', $route)
  136. ->with('endpointId', $route['methods'][0].str_replace(['/', '?', '{', '}', ':'], '-', $route['uri']))
  137. ->with('settings', $settings)
  138. ->with('auth', $auth)
  139. ->with('baseUrl', $this->baseUrl)
  140. ->render();
  141. return $route;
  142. });
  143. });
  144. return $routesWithOutput;
  145. }
  146. protected function writePostmanCollection(Collection $parsedRoutes): void
  147. {
  148. if ($this->shouldGeneratePostmanCollection) {
  149. ConsoleOutputUtils::info('Generating Postman collection');
  150. $collection = $this->generatePostmanCollection($parsedRoutes);
  151. if ($this->isStatic) {
  152. $collectionPath = "{$this->staticTypeOutputPath}/collection.json";
  153. file_put_contents($collectionPath, $collection);
  154. } else {
  155. Storage::disk('local')->put('scribe/collection.json', $collection);
  156. $collectionPath = 'storage/app/scribe/collection.json';
  157. }
  158. ConsoleOutputUtils::success("Wrote Postman collection to: {$collectionPath}");
  159. }
  160. }
  161. protected function writeOpenAPISpec(Collection $parsedRoutes): void
  162. {
  163. if ($this->shouldGenerateOpenAPISpec) {
  164. ConsoleOutputUtils::info('Generating OpenAPI specification');
  165. $spec = $this->generateOpenAPISpec($parsedRoutes);
  166. if ($this->isStatic) {
  167. $specPath = "{$this->staticTypeOutputPath}/openapi.yaml";
  168. file_put_contents($specPath, $spec);
  169. } else {
  170. Storage::disk('local')->put('scribe/openapi.yaml', $spec);
  171. $specPath = 'storage/app/scribe/openapi.yaml';
  172. }
  173. ConsoleOutputUtils::success("Wrote OpenAPI specification to: {$specPath}");
  174. }
  175. }
  176. /**
  177. * Generate Postman collection JSON file.
  178. *
  179. * @param Collection $groupedEndpoints
  180. *
  181. * @return string
  182. */
  183. public function generatePostmanCollection(Collection $groupedEndpoints)
  184. {
  185. /** @var PostmanCollectionWriter $writer */
  186. $writer = app()->makeWith(
  187. PostmanCollectionWriter::class,
  188. ['config' => $this->config]
  189. );
  190. $collection = $writer->generatePostmanCollection($groupedEndpoints);
  191. $overrides = $this->config->get('postman.overrides', []);
  192. if (count($overrides)) {
  193. foreach ($overrides as $key => $value) {
  194. data_set($collection, $key, $value);
  195. }
  196. }
  197. return json_encode($collection, JSON_PRETTY_PRINT);
  198. }
  199. public function generateOpenAPISpec(Collection $groupedEndpoints)
  200. {
  201. /** @var OpenAPISpecWriter $writer */
  202. $writer = app()->makeWith(
  203. OpenAPISpecWriter::class,
  204. ['config' => $this->config]
  205. );
  206. $spec = $writer->generateSpecContent($groupedEndpoints);
  207. $overrides = $this->config->get('openapi.overrides', []);
  208. if (count($overrides)) {
  209. foreach ($overrides as $key => $value) {
  210. data_set($spec, $key, $value);
  211. }
  212. }
  213. return Yaml::dump($spec, 10, 4, Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP);
  214. }
  215. protected function performFinalTasksForLaravelType(): void
  216. {
  217. if (!is_dir($this->laravelTypeOutputPath)) {
  218. mkdir($this->laravelTypeOutputPath, 0777, true);
  219. }
  220. $publicDirectory = app()->get('path.public');
  221. if (!is_dir("$publicDirectory/vendor/scribe")) {
  222. mkdir("$publicDirectory/vendor/scribe", 0777, true);
  223. }
  224. // Transform output HTML to a Blade view
  225. rename("{$this->staticTypeOutputPath}/index.html", "$this->laravelTypeOutputPath/index.blade.php");
  226. // Move assets from public/docs to $publicDirectory/vendor/scribe
  227. // We need to do this delete first, otherwise move won't work if folder exists
  228. Utils::deleteDirectoryAndContents("$publicDirectory/vendor/scribe/", getcwd());
  229. rename("{$this->staticTypeOutputPath}/", "$publicDirectory/vendor/scribe/");
  230. $contents = file_get_contents("$this->laravelTypeOutputPath/index.blade.php");
  231. // Rewrite links to go through Laravel
  232. $contents = preg_replace('#href="css/(.+?)"#', 'href="{{ asset("vendor/scribe/css/$1") }}"', $contents);
  233. $contents = preg_replace('#src="(js|images)/(.+?)"#', 'src="{{ asset("vendor/scribe/$1/$2") }}"', $contents);
  234. $contents = str_replace('href="./collection.json"', 'href="{{ route("scribe.postman") }}"', $contents);
  235. $contents = str_replace('href="./openapi.yaml"', 'href="{{ route("scribe.openapi") }}"', $contents);
  236. file_put_contents("$this->laravelTypeOutputPath/index.blade.php", $contents);
  237. }
  238. public function writeHtmlDocs(): void
  239. {
  240. ConsoleOutputUtils::info('Transforming Markdown docs to HTML...');
  241. $this->pastel->generate($this->sourceOutputPath . '/index.md', $this->staticTypeOutputPath);
  242. // Add our custom JS
  243. copy(__DIR__.'/../../resources/js/tryitout.js', $this->staticTypeOutputPath . '/js/tryitout-'.Globals::SCRIBE_VERSION.'.js');
  244. if (!$this->isStatic) {
  245. $this->performFinalTasksForLaravelType();
  246. }
  247. ConsoleOutputUtils::success("Wrote HTML documentation to: " . ($this->isStatic ? $this->staticTypeOutputPath : $this->laravelTypeOutputPath));
  248. }
  249. protected function writeIndexMarkdownFile(array $settings): void
  250. {
  251. $indexMarkdownFile = $this->sourceOutputPath . '/index.md';
  252. if ($this->hasFileBeenModified($indexMarkdownFile)) {
  253. if ($this->shouldOverwrite) {
  254. ConsoleOutputUtils::warn("Discarding manual changes for file $indexMarkdownFile because you specified --force");
  255. } else {
  256. ConsoleOutputUtils::warn("Skipping modified file $indexMarkdownFile");
  257. return;
  258. }
  259. }
  260. $frontmatter = view('scribe::partials.frontmatter')
  261. ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection)
  262. ->with('showOpenAPISpecButton', $this->shouldGenerateOpenAPISpec)
  263. // These paths are wrong for laravel type but will be replaced in the performFinalTasksForLaravelType() method
  264. ->with('postmanCollectionLink', './collection.json')
  265. ->with('openAPISpecLink', './openapi.yaml')
  266. ->with('outputPath', 'docs')
  267. ->with('settings', $settings);
  268. $introText = $this->config->get('intro_text', '');
  269. $introMarkdown = view('scribe::index')
  270. ->with('frontmatter', $frontmatter)
  271. ->with('description', $this->config->get('description', ''))
  272. ->with('introText', $introText)
  273. ->with('baseUrl', $this->baseUrl)
  274. ->with('isInteractive', $this->config->get('interactive', true));
  275. $this->writeFile($indexMarkdownFile, $introMarkdown);
  276. }
  277. protected function writeAuthMarkdownFile(): void
  278. {
  279. $authMarkdownFile = $this->sourceOutputPath . '/authentication.md';
  280. if ($this->hasFileBeenModified($authMarkdownFile)) {
  281. if ($this->shouldOverwrite) {
  282. ConsoleOutputUtils::warn("Discarding manual changes for file $authMarkdownFile because you specified --force");
  283. } else {
  284. ConsoleOutputUtils::warn("Skipping modified file $authMarkdownFile");
  285. return;
  286. }
  287. }
  288. $isAuthed = $this->config->get('auth.enabled', false);
  289. $authDescription = '';
  290. $extraInfo = '';
  291. if ($isAuthed) {
  292. $strategy = $this->config->get('auth.in');
  293. $parameterName = $this->config->get('auth.name');
  294. $authDescription = Arr::random([
  295. "This API is authenticated by sending ",
  296. "To authenticate requests, include ",
  297. "Authenticate requests to this API's endpoints by sending ",
  298. ]);
  299. switch ($strategy) {
  300. case 'query':
  301. $authDescription .= "a query parameter **`$parameterName`** in the request.";
  302. break;
  303. case 'body':
  304. $authDescription .= "a parameter **`$parameterName`** in the body of the request.";
  305. break;
  306. case 'query_or_body':
  307. $authDescription .= "a parameter **`$parameterName`** either in the query string or in the request body.";
  308. break;
  309. case 'bearer':
  310. $authDescription .= sprintf('an **`Authorization`** header with the value **`"Bearer %s"`**.', $this->config->get('auth.placeholder') ?: 'your-token');;
  311. break;
  312. case 'basic':
  313. $authDescription .= "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.";
  314. break;
  315. case 'header':
  316. $authDescription .= sprintf('a **`%s`** header with the value **`"%s"`**.', $parameterName, $this->config->get('auth.placeholder') ?: 'your-token');
  317. break;
  318. }
  319. $authDescription .= "\n\nAll authenticated endpoints are marked with a `requires authentication` badge in the documentation below.";
  320. $extraInfo = $this->config->get('auth.extra_info', '');
  321. }
  322. $authMarkdown = view('scribe::authentication', [
  323. 'isAuthed' => $isAuthed,
  324. 'authDescription' => $authDescription,
  325. 'extraAuthInfo' => $extraInfo,
  326. ]);
  327. $this->writeFile($authMarkdownFile, $authMarkdown);
  328. }
  329. protected function writeEndpointsMarkdownFile(Collection $parsedRoutes, array $settings): void
  330. {
  331. if (!is_dir($this->sourceOutputPath . '/groups')) {
  332. mkdir($this->sourceOutputPath . '/groups', 0777, true);
  333. }
  334. // Generate Markdown for each route. Not using a Blade component bc of some complex logic
  335. $parsedRoutesWithOutput = $this->generateMarkdownOutputForEachRoute($parsedRoutes, $settings);
  336. $groupFileNames = $parsedRoutesWithOutput->map(function ($routesInGroup, $groupName) {
  337. $groupId = Str::slug($groupName);
  338. $routeGroupMarkdownFile = $this->sourceOutputPath . "/groups/$groupId.md";
  339. if ($this->hasFileBeenModified($routeGroupMarkdownFile)) {
  340. if ($this->shouldOverwrite) {
  341. ConsoleOutputUtils::warn("Discarding manual changes for file $routeGroupMarkdownFile because you specified --force");
  342. } else {
  343. ConsoleOutputUtils::warn("Skipping modified file $routeGroupMarkdownFile");
  344. return "$groupId.md";
  345. }
  346. }
  347. $groupDescription = Arr::first($routesInGroup, function ($route) {
  348. return $route['metadata']['groupDescription'] !== '';
  349. })['metadata']['groupDescription'] ?? '';
  350. $groupMarkdown = view('scribe::partials.group')
  351. ->with('groupName', $groupName)
  352. ->with('groupDescription', $groupDescription)
  353. ->with('routes', $routesInGroup);
  354. $this->writeFile($routeGroupMarkdownFile, $groupMarkdown);
  355. return "$groupId.md";
  356. })->toArray();
  357. // Now, we need to delete any other Markdown files in the groups/ directory.
  358. // Why? Because, if we don't, if a user renames a group, the old file will still exist,
  359. // so the docs will have those endpoints repeated under the two groups.
  360. $filesInGroupFolder = scandir($this->sourceOutputPath . "/groups");
  361. $filesNotPresentInThisRun = collect($filesInGroupFolder)->filter(function ($fileName) use ($groupFileNames) {
  362. if (in_array($fileName, ['.', '..'])) {
  363. return false;
  364. }
  365. return !Str::is($groupFileNames, $fileName);
  366. });
  367. $filesNotPresentInThisRun->each(function ($fileName) {
  368. unlink($this->sourceOutputPath . "/groups/$fileName");
  369. });
  370. }
  371. /**
  372. */
  373. protected function writeFile(string $filePath, $markdown): void
  374. {
  375. file_put_contents($filePath, $markdown);
  376. $this->lastTimesWeModifiedTheseFiles[$filePath] = time();
  377. }
  378. /**
  379. */
  380. protected function writeModificationTimesTrackingFile(): void
  381. {
  382. $content = "# GENERATED. YOU SHOULDN'T MODIFY OR DELETE THIS FILE.\n";
  383. $content .= "# Scribe uses this file to know when you change something manually in your docs.\n";
  384. $content .= collect($this->lastTimesWeModifiedTheseFiles)
  385. ->map(function ($mtime, $filePath) {
  386. return "$filePath=$mtime";
  387. })->implode("\n");
  388. file_put_contents($this->fileModificationTimesFile, $content);
  389. }
  390. /**
  391. */
  392. protected function hasFileBeenModified(string $filePath): bool
  393. {
  394. if (!file_exists($filePath)) {
  395. return false;
  396. }
  397. $oldFileModificationTime = $this->lastTimesWeModifiedTheseFiles[$filePath] ?? null;
  398. if ($oldFileModificationTime) {
  399. $latestFileModifiedTime = filemtime($filePath);
  400. $wasFileModifiedManually = $latestFileModifiedTime > (int)$oldFileModificationTime;
  401. return $wasFileModifiedManually;
  402. }
  403. return false;
  404. }
  405. protected function fetchLastTimeWeModifiedFilesFromTrackingFile()
  406. {
  407. if (file_exists($this->fileModificationTimesFile)) {
  408. $lastTimesWeModifiedTheseFiles = explode("\n", trim(file_get_contents($this->fileModificationTimesFile)));
  409. // First two lines are comments
  410. array_shift($lastTimesWeModifiedTheseFiles);
  411. array_shift($lastTimesWeModifiedTheseFiles);
  412. $this->lastTimesWeModifiedTheseFiles = collect($lastTimesWeModifiedTheseFiles)
  413. ->mapWithKeys(function ($line) {
  414. [$filePath, $modificationTime] = explode("=", $line);
  415. return [$filePath => $modificationTime];
  416. })->toArray();
  417. }
  418. }
  419. }