Writer.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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\Flags;
  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. if (!is_dir("public/vendor/scribe")) {
  221. mkdir("public/vendor/scribe", 0777, true);
  222. }
  223. // Transform output HTML to a Blade view
  224. rename("{$this->staticTypeOutputPath}/index.html", "$this->laravelTypeOutputPath/index.blade.php");
  225. // Move assets from public/docs to public/vendor/scribe
  226. // We need to do this delete first, otherwise move won't work if folder exists
  227. Utils::deleteDirectoryAndContents("public/vendor/scribe/", getcwd());
  228. rename("{$this->staticTypeOutputPath}/", "public/vendor/scribe/");
  229. $contents = file_get_contents("$this->laravelTypeOutputPath/index.blade.php");
  230. // Rewrite links to go through Laravel
  231. $contents = preg_replace('#href="css/(.+?)"#', 'href="{{ asset("vendor/scribe/css/$1") }}"', $contents);
  232. $contents = preg_replace('#src="(js|images)/(.+?)"#', 'src="{{ asset("vendor/scribe/$1/$2") }}"', $contents);
  233. $contents = str_replace('href="./collection.json"', 'href="{{ route("scribe.postman") }}"', $contents);
  234. $contents = str_replace('href="./openapi.yaml"', 'href="{{ route("scribe.openapi") }}"', $contents);
  235. file_put_contents("$this->laravelTypeOutputPath/index.blade.php", $contents);
  236. }
  237. public function writeHtmlDocs(): void
  238. {
  239. ConsoleOutputUtils::info('Transforming Markdown docs to HTML...');
  240. $this->pastel->generate($this->sourceOutputPath . '/index.md', $this->staticTypeOutputPath);
  241. // Add our custom JS
  242. copy(__DIR__.'/../../resources/js/tryitout.js', $this->staticTypeOutputPath . '/js/tryitout-'.Flags::SCRIBE_VERSION.'.js');
  243. if (!$this->isStatic) {
  244. $this->performFinalTasksForLaravelType();
  245. }
  246. ConsoleOutputUtils::success("Wrote HTML documentation to: " . ($this->isStatic ? $this->staticTypeOutputPath : $this->laravelTypeOutputPath));
  247. }
  248. protected function writeIndexMarkdownFile(array $settings): void
  249. {
  250. $indexMarkdownFile = $this->sourceOutputPath . '/index.md';
  251. if ($this->hasFileBeenModified($indexMarkdownFile)) {
  252. if ($this->shouldOverwrite) {
  253. ConsoleOutputUtils::warn("Discarding manual changes for file $indexMarkdownFile because you specified --force");
  254. } else {
  255. ConsoleOutputUtils::warn("Skipping modified file $indexMarkdownFile");
  256. return;
  257. }
  258. }
  259. $frontmatter = view('scribe::partials.frontmatter')
  260. ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection)
  261. ->with('showOpenAPISpecButton', $this->shouldGenerateOpenAPISpec)
  262. // These paths are wrong for laravel type but will be replaced in the performFinalTasksForLaravelType() method
  263. ->with('postmanCollectionLink', './collection.json')
  264. ->with('openAPISpecLink', './openapi.yaml')
  265. ->with('outputPath', 'docs')
  266. ->with('settings', $settings);
  267. $introText = $this->config->get('intro_text', '');
  268. $introMarkdown = view('scribe::index')
  269. ->with('frontmatter', $frontmatter)
  270. ->with('description', $this->config->get('description', ''))
  271. ->with('introText', $introText)
  272. ->with('baseUrl', $this->baseUrl)
  273. ->with('isInteractive', $this->config->get('interactive', true));
  274. $this->writeFile($indexMarkdownFile, $introMarkdown);
  275. }
  276. protected function writeAuthMarkdownFile(): void
  277. {
  278. $authMarkdownFile = $this->sourceOutputPath . '/authentication.md';
  279. if ($this->hasFileBeenModified($authMarkdownFile)) {
  280. if ($this->shouldOverwrite) {
  281. ConsoleOutputUtils::warn("Discarding manual changes for file $authMarkdownFile because you specified --force");
  282. } else {
  283. ConsoleOutputUtils::warn("Skipping modified file $authMarkdownFile");
  284. return;
  285. }
  286. }
  287. $isAuthed = $this->config->get('auth.enabled', false);
  288. $authDescription = '';
  289. $extraInfo = '';
  290. if ($isAuthed) {
  291. $strategy = $this->config->get('auth.in');
  292. $parameterName = $this->config->get('auth.name');
  293. $authDescription = Arr::random([
  294. "This API is authenticated by sending ",
  295. "To authenticate requests, include ",
  296. "Authenticate requests to this API's endpoints by sending ",
  297. ]);
  298. switch ($strategy) {
  299. case 'query':
  300. $authDescription .= "a query parameter **`$parameterName`** in the request.";
  301. break;
  302. case 'body':
  303. $authDescription .= "a parameter **`$parameterName`** in the body of the request.";
  304. break;
  305. case 'query_or_body':
  306. $authDescription .= "a parameter **`$parameterName`** either in the query string or in the request body.";
  307. break;
  308. case 'bearer':
  309. $authDescription .= sprintf('an **`Authorization`** header with the value **`"Bearer %s"`**.', $this->config->get('auth.placeholder') ?: 'your-token');;
  310. break;
  311. case 'basic':
  312. $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.";
  313. break;
  314. case 'header':
  315. $authDescription .= sprintf('a **`%s`** header with the value **`"%s"`**.', $parameterName, $this->config->get('auth.placeholder') ?: 'your-token');
  316. break;
  317. }
  318. $authDescription .= '\n\nAll authenticated endpoints are marked with a `requires authentication` badge in the documentation below.';
  319. $extraInfo = $this->config->get('auth.extra_info', '');
  320. }
  321. $authMarkdown = view('scribe::authentication', [
  322. 'isAuthed' => $isAuthed,
  323. 'authDescription' => $authDescription,
  324. 'extraAuthInfo' => $extraInfo,
  325. ]);
  326. $this->writeFile($authMarkdownFile, $authMarkdown);
  327. }
  328. protected function writeEndpointsMarkdownFile(Collection $parsedRoutes, array $settings): void
  329. {
  330. if (!is_dir($this->sourceOutputPath . '/groups')) {
  331. mkdir($this->sourceOutputPath . '/groups', 0777, true);
  332. }
  333. // Generate Markdown for each route. Not using a Blade component bc of some complex logic
  334. $parsedRoutesWithOutput = $this->generateMarkdownOutputForEachRoute($parsedRoutes, $settings);
  335. $groupFileNames = $parsedRoutesWithOutput->map(function ($routesInGroup, $groupName) {
  336. $groupId = Str::slug($groupName);
  337. $routeGroupMarkdownFile = $this->sourceOutputPath . "/groups/$groupId.md";
  338. if ($this->hasFileBeenModified($routeGroupMarkdownFile)) {
  339. if ($this->shouldOverwrite) {
  340. ConsoleOutputUtils::warn("Discarding manual changes for file $routeGroupMarkdownFile because you specified --force");
  341. } else {
  342. ConsoleOutputUtils::warn("Skipping modified file $routeGroupMarkdownFile");
  343. return "$groupId.md";
  344. }
  345. }
  346. $groupDescription = Arr::first($routesInGroup, function ($route) {
  347. return $route['metadata']['groupDescription'] !== '';
  348. })['metadata']['groupDescription'] ?? '';
  349. $groupMarkdown = view('scribe::partials.group')
  350. ->with('groupName', $groupName)
  351. ->with('groupDescription', $groupDescription)
  352. ->with('routes', $routesInGroup);
  353. $this->writeFile($routeGroupMarkdownFile, $groupMarkdown);
  354. return "$groupId.md";
  355. })->toArray();
  356. // Now, we need to delete any other Markdown files in the groups/ directory.
  357. // Why? Because, if we don't, if a user renames a group, the old file will still exist,
  358. // so the docs will have those endpoints repeated under the two groups.
  359. $filesInGroupFolder = scandir($this->sourceOutputPath . "/groups");
  360. $filesNotPresentInThisRun = collect($filesInGroupFolder)->filter(function ($fileName) use ($groupFileNames) {
  361. if (in_array($fileName, ['.', '..'])) {
  362. return false;
  363. }
  364. return !Str::is($groupFileNames, $fileName);
  365. });
  366. $filesNotPresentInThisRun->each(function ($fileName) {
  367. unlink($this->sourceOutputPath . "/groups/$fileName");
  368. });
  369. }
  370. /**
  371. */
  372. protected function writeFile(string $filePath, $markdown): void
  373. {
  374. file_put_contents($filePath, $markdown);
  375. $this->lastTimesWeModifiedTheseFiles[$filePath] = time();
  376. }
  377. /**
  378. */
  379. protected function writeModificationTimesTrackingFile(): void
  380. {
  381. $content = "# GENERATED. YOU SHOULDN'T MODIFY OR DELETE THIS FILE.\n";
  382. $content .= "# Scribe uses this file to know when you change something manually in your docs.\n";
  383. $content .= collect($this->lastTimesWeModifiedTheseFiles)
  384. ->map(function ($mtime, $filePath) {
  385. return "$filePath=$mtime";
  386. })->implode("\n");
  387. file_put_contents($this->fileModificationTimesFile, $content);
  388. }
  389. /**
  390. */
  391. protected function hasFileBeenModified(string $filePath): bool
  392. {
  393. if (!file_exists($filePath)) {
  394. return false;
  395. }
  396. $oldFileModificationTime = $this->lastTimesWeModifiedTheseFiles[$filePath] ?? null;
  397. if ($oldFileModificationTime) {
  398. $latestFileModifiedTime = filemtime($filePath);
  399. $wasFileModifiedManually = $latestFileModifiedTime > (int)$oldFileModificationTime;
  400. return $wasFileModifiedManually;
  401. }
  402. return false;
  403. }
  404. protected function fetchLastTimeWeModifiedFilesFromTrackingFile()
  405. {
  406. if (file_exists($this->fileModificationTimesFile)) {
  407. $lastTimesWeModifiedTheseFiles = explode("\n", trim(file_get_contents($this->fileModificationTimesFile)));
  408. // First two lines are comments
  409. array_shift($lastTimesWeModifiedTheseFiles);
  410. array_shift($lastTimesWeModifiedTheseFiles);
  411. $this->lastTimesWeModifiedTheseFiles = collect($lastTimesWeModifiedTheseFiles)
  412. ->mapWithKeys(function ($line) {
  413. [$filePath, $modificationTime] = explode("=", $line);
  414. return [$filePath => $modificationTime];
  415. })->toArray();
  416. }
  417. }
  418. }