OutputTest.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. namespace Knuckles\Scribe\Tests\GenerateDocumentation;
  3. use Illuminate\Support\Facades\Route as RouteFacade;
  4. use Illuminate\Support\Facades\Storage;
  5. use Illuminate\Support\Facades\View;
  6. use Knuckles\Scribe\Tests\BaseLaravelTest;
  7. use Knuckles\Scribe\Tests\Fixtures\TestController;
  8. use Knuckles\Scribe\Tests\Fixtures\TestGroupController;
  9. use Knuckles\Scribe\Tests\Fixtures\TestPartialResourceController;
  10. use Knuckles\Scribe\Tests\Fixtures\TestPost;
  11. use Knuckles\Scribe\Tests\Fixtures\TestPostBoundInterface;
  12. use Knuckles\Scribe\Tests\Fixtures\TestPostController;
  13. use Knuckles\Scribe\Tests\Fixtures\TestPostBoundInterfaceController;
  14. use Knuckles\Scribe\Tests\Fixtures\TestPostUserController;
  15. use Knuckles\Scribe\Tests\Fixtures\TestUser;
  16. use Knuckles\Scribe\Tests\TestHelpers;
  17. use Knuckles\Scribe\Tools\Utils;
  18. use Symfony\Component\DomCrawler\Crawler;
  19. use Symfony\Component\Yaml\Yaml;
  20. use Knuckles\Scribe\Extracting\Strategies;
  21. class OutputTest extends BaseLaravelTest
  22. {
  23. use TestHelpers;
  24. protected function setUp(): void
  25. {
  26. parent::setUp();
  27. config(['scribe.strategies' => [
  28. 'metadata' => [
  29. Strategies\Metadata\GetFromDocBlocks::class,
  30. Strategies\Metadata\GetFromMetadataAttributes::class,
  31. ],
  32. 'urlParameters' => [
  33. Strategies\UrlParameters\GetFromLaravelAPI::class,
  34. Strategies\UrlParameters\GetFromLumenAPI::class,
  35. Strategies\UrlParameters\GetFromUrlParamAttribute::class,
  36. Strategies\UrlParameters\GetFromUrlParamTag::class,
  37. ],
  38. 'queryParameters' => [
  39. Strategies\QueryParameters\GetFromFormRequest::class,
  40. Strategies\QueryParameters\GetFromInlineValidator::class,
  41. Strategies\QueryParameters\GetFromQueryParamAttribute::class,
  42. Strategies\QueryParameters\GetFromQueryParamTag::class,
  43. ],
  44. 'headers' => [
  45. Strategies\Headers\GetFromRouteRules::class,
  46. Strategies\Headers\GetFromHeaderAttribute::class,
  47. Strategies\Headers\GetFromHeaderTag::class,
  48. ],
  49. 'bodyParameters' => [
  50. Strategies\BodyParameters\GetFromFormRequest::class,
  51. Strategies\BodyParameters\GetFromInlineValidator::class,
  52. Strategies\BodyParameters\GetFromBodyParamAttribute::class,
  53. Strategies\BodyParameters\GetFromBodyParamTag::class,
  54. ],
  55. 'responses' => [
  56. Strategies\Responses\UseResponseAttributes::class,
  57. Strategies\Responses\UseTransformerTags::class,
  58. Strategies\Responses\UseApiResourceTags::class,
  59. Strategies\Responses\UseResponseTag::class,
  60. Strategies\Responses\UseResponseFileTag::class,
  61. Strategies\Responses\ResponseCalls::class,
  62. ],
  63. 'responseFields' => [
  64. Strategies\ResponseFields\GetFromResponseFieldAttribute::class,
  65. Strategies\ResponseFields\GetFromResponseFieldTag::class,
  66. ],
  67. ],
  68. ]);
  69. config(['scribe.database_connections_to_transact' => []]);
  70. config(['scribe.routes.0.match.prefixes' => ['api/*']]);
  71. // Skip these ones for faster tests
  72. config(['scribe.openapi.enabled' => false]);
  73. config(['scribe.postman.enabled' => false]);
  74. // We want to have the same values for params each time
  75. config(['scribe.examples.faker_seed' => 1234]);
  76. $factory = app(\Illuminate\Database\Eloquent\Factory::class);
  77. $factory->define(TestUser::class, function () {
  78. return [
  79. 'id' => 4,
  80. 'first_name' => 'Tested',
  81. 'last_name' => 'Again',
  82. 'email' => 'a@b.com',
  83. ];
  84. });
  85. }
  86. public function tearDown(): void
  87. {
  88. Utils::deleteDirectoryAndContents('public/docs');
  89. Utils::deleteDirectoryAndContents('.scribe');
  90. }
  91. protected function usingLaravelTypeDocs($app)
  92. {
  93. $app['config']->set('scribe.type', 'laravel');
  94. $app['config']->set('scribe.laravel.add_routes', true);
  95. $app['config']->set('scribe.laravel.docs_url', '/apidocs');
  96. }
  97. /**
  98. * @test
  99. * @define-env usingLaravelTypeDocs
  100. */
  101. public function generates_laravel_type_output()
  102. {
  103. RouteFacade::post('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  104. config(['scribe.postman.enabled' => true]);
  105. config(['scribe.openapi.enabled' => true]);
  106. $this->generate();
  107. $this->assertFileExists($this->postmanOutputPath(true));
  108. $this->assertFileExists($this->openapiOutputPath(true));
  109. $this->assertFileExists($this->bladeOutputPath());
  110. $response = $this->get('/apidocs/');
  111. $response->assertStatus(200);
  112. $response = $this->get('/apidocs.postman');
  113. $response->assertStatus(200);
  114. $response = $this->get('/apidocs.openapi');
  115. $response->assertStatus(200);
  116. unlink($this->postmanOutputPath(true));
  117. unlink($this->openapiOutputPath(true));
  118. unlink($this->bladeOutputPath());
  119. }
  120. /** @test */
  121. public function supports_multi_docs_in_laravel_type_output()
  122. {
  123. RouteFacade::post('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  124. config(['scribe_admin' => config('scribe')]);
  125. $title = "The Real Admin API";
  126. config(['scribe_admin.title' => $title]);
  127. config(['scribe_admin.type' => 'laravel']);
  128. config(['scribe_admin.postman.enabled' => true]);
  129. config(['scribe_admin.openapi.enabled' => true]);
  130. $this->generate(["--config" => "scribe_admin"]);
  131. $paths = collect([
  132. Storage::disk('local')->path('scribe_admin/collection.json'),
  133. Storage::disk('local')->path('scribe_admin/openapi.yaml'),
  134. View::getFinder()->find('scribe_admin/index'),
  135. ]);
  136. $paths->each(fn($path) => $this->assertFileContainsString($path, $title));
  137. $paths->each(fn($path) => unlink($path));
  138. $this->assertDirectoryExists(".scribe_admin");
  139. Utils::deleteDirectoryAndContents(".scribe_admin");
  140. }
  141. /** @test */
  142. public function generated_postman_collection_file_is_correct()
  143. {
  144. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  145. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  146. RouteFacade::post('/api/withBodyParameters', [TestController::class, 'withBodyParameters']);
  147. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  148. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  149. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  150. config(['scribe.title' => 'GREAT API!']);
  151. config(['scribe.auth.enabled' => true]);
  152. config(['scribe.postman.overrides' => [
  153. 'info.version' => '3.9.9',
  154. ]]);
  155. config([
  156. 'scribe.routes.0.apply.headers' => [
  157. 'Custom-Header' => 'NotSoCustom',
  158. ],
  159. ]);
  160. config(['scribe.postman.enabled' => true]);
  161. $this->generate();
  162. $generatedCollection = json_decode(file_get_contents($this->postmanOutputPath()), true);
  163. // The Postman ID varies from call to call; erase it to make the test data reproducible.
  164. $generatedCollection['info']['_postman_id'] = '';
  165. $fixtureCollection = json_decode(file_get_contents(__DIR__ . '/../Fixtures/collection.json'), true);
  166. $this->assertEquals($fixtureCollection, $generatedCollection);
  167. }
  168. /** @test */
  169. public function generated_openapi_spec_file_is_correct()
  170. {
  171. RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
  172. RouteFacade::post('/api/withFormDataParams', [TestController::class, 'withFormDataParams']);
  173. RouteFacade::get('/api/withResponseTag', [TestController::class, 'withResponseTag']);
  174. RouteFacade::get('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
  175. RouteFacade::get('/api/withAuthTag', [TestController::class, 'withAuthenticatedTag']);
  176. RouteFacade::get('/api/echoesUrlParameters/{param}/{param2}/{param3?}/{param4?}', [TestController::class, 'echoesUrlParameters']);
  177. config(['scribe.openapi.enabled' => true]);
  178. config(['scribe.openapi.overrides' => [
  179. 'info.version' => '3.9.9',
  180. ]]);
  181. config([
  182. 'scribe.routes.0.apply.headers' => [
  183. 'Custom-Header' => 'NotSoCustom',
  184. ],
  185. ]);
  186. $this->generate();
  187. $generatedSpec = Yaml::parseFile($this->openapiOutputPath());
  188. $fixtureSpec = Yaml::parseFile(__DIR__ . '/../Fixtures/openapi.yaml');
  189. $this->assertEquals($fixtureSpec, $generatedSpec);
  190. }
  191. /** @test */
  192. public function can_append_custom_http_headers()
  193. {
  194. RouteFacade::get('/api/headers', [TestController::class, 'checkCustomHeaders']);
  195. config([
  196. 'scribe.routes.0.apply.headers' => [
  197. 'Authorization' => 'customAuthToken',
  198. 'Custom-Header' => 'NotSoCustom',
  199. ],
  200. ]);
  201. $this->generate();
  202. $endpointDetails = Yaml::parseFile('.scribe/endpoints/00.yaml')['endpoints'][0];
  203. $this->assertEquals("customAuthToken", $endpointDetails['headers']["Authorization"]);
  204. $this->assertEquals("NotSoCustom", $endpointDetails['headers']["Custom-Header"]);
  205. }
  206. /** @test */
  207. public function can_parse_utf8_response()
  208. {
  209. RouteFacade::get('/api/utf8', [TestController::class, 'withUtf8ResponseTag']);
  210. $this->generate();
  211. $generatedHtml = file_get_contents($this->htmlOutputPath());
  212. $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedHtml);
  213. }
  214. /** @test */
  215. public function sorts_group_naturally()
  216. {
  217. RouteFacade::get('/api/action1', TestGroupController::class . '@action1');
  218. RouteFacade::get('/api/action1b', TestGroupController::class . '@action1b');
  219. RouteFacade::get('/api/action2', TestGroupController::class . '@action2');
  220. RouteFacade::get('/api/action10', TestGroupController::class . '@action10');
  221. $this->generate();
  222. $this->assertEquals('1. Group 1', Yaml::parseFile('.scribe/endpoints/00.yaml')['name']);
  223. $this->assertEquals('2. Group 2', Yaml::parseFile('.scribe/endpoints/01.yaml')['name']);
  224. $this->assertEquals('10. Group 10', Yaml::parseFile('.scribe/endpoints/02.yaml')['name']);
  225. }
  226. /** @test */
  227. public function sorts_groups_and_endpoints_in_the_specified_order()
  228. {
  229. config(['scribe.groups.order' => [
  230. '10. Group 10',
  231. '1. Group 1' => [
  232. 'GET /api/action1b',
  233. 'GET /api/action1',
  234. ],
  235. '13. Group 13' => [
  236. 'SG B' => [
  237. 'POST /api/action13d',
  238. 'GET /api/action13a',
  239. ],
  240. 'SG A',
  241. 'PUT /api/action13c',
  242. 'POST /api/action13b',
  243. ],
  244. ]]);
  245. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  246. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  247. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  248. RouteFacade::get('/api/action10', [TestGroupController::class, 'action10']);
  249. RouteFacade::get('/api/action13a', [TestGroupController::class, 'action13a']);
  250. RouteFacade::post('/api/action13b', [TestGroupController::class, 'action13b']);
  251. RouteFacade::put('/api/action13c', [TestGroupController::class, 'action13c']);
  252. RouteFacade::post('/api/action13d', [TestGroupController::class, 'action13d']);
  253. RouteFacade::get('/api/action13e', [TestGroupController::class, 'action13e']);
  254. $this->generate();
  255. $this->assertEquals('10. Group 10', Yaml::parseFile('.scribe/endpoints/00.yaml')['name']);
  256. $secondGroup = Yaml::parseFile('.scribe/endpoints/01.yaml');
  257. $this->assertEquals('1. Group 1', $secondGroup['name']);
  258. $thirdGroup = Yaml::parseFile('.scribe/endpoints/02.yaml');
  259. $this->assertEquals('13. Group 13', $thirdGroup['name']);
  260. $this->assertEquals('2. Group 2', Yaml::parseFile('.scribe/endpoints/03.yaml')['name']);
  261. $this->assertEquals('api/action1b', $secondGroup['endpoints'][0]['uri']);
  262. $this->assertEquals('GET', $secondGroup['endpoints'][0]['httpMethods'][0]);
  263. $this->assertEquals('api/action1', $secondGroup['endpoints'][1]['uri']);
  264. $this->assertEquals('GET', $secondGroup['endpoints'][1]['httpMethods'][0]);
  265. $this->assertEquals('api/action13d', $thirdGroup['endpoints'][0]['uri']);
  266. $this->assertEquals('POST', $thirdGroup['endpoints'][0]['httpMethods'][0]);
  267. $this->assertEquals('api/action13a', $thirdGroup['endpoints'][1]['uri']);
  268. $this->assertEquals('GET', $thirdGroup['endpoints'][1]['httpMethods'][0]);
  269. $this->assertEquals('api/action13e', $thirdGroup['endpoints'][2]['uri']);
  270. $this->assertEquals('GET', $thirdGroup['endpoints'][2]['httpMethods'][0]);
  271. $this->assertEquals('api/action13c', $thirdGroup['endpoints'][3]['uri']);
  272. $this->assertEquals('PUT', $thirdGroup['endpoints'][3]['httpMethods'][0]);
  273. $this->assertEquals('api/action13b', $thirdGroup['endpoints'][4]['uri']);
  274. $this->assertEquals('POST', $thirdGroup['endpoints'][4]['httpMethods'][0]);
  275. }
  276. /** @test */
  277. public function will_not_overwrite_manually_modified_content_unless_force_flag_is_set()
  278. {
  279. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  280. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  281. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  282. $this->generate();
  283. $authFilePath = '.scribe/auth.md';
  284. $group1FilePath = '.scribe/endpoints/00.yaml';
  285. $group = Yaml::parseFile($group1FilePath);
  286. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  287. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  288. $extraParam = [
  289. 'name' => 'a_param',
  290. 'description' => 'A URL param.',
  291. 'required' => true,
  292. 'example' => 6,
  293. 'type' => 'integer',
  294. 'custom' => [],
  295. ];
  296. $group['endpoints'][0]['urlParameters']['a_param'] = $extraParam;
  297. file_put_contents($group1FilePath, Yaml::dump(
  298. $group, 20, 2,
  299. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  300. ));
  301. file_put_contents($authFilePath, 'Some other useful stuff.', FILE_APPEND);
  302. $this->generate();
  303. $group = Yaml::parseFile($group1FilePath);
  304. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  305. $this->assertEquals(['a_param' => $extraParam], $group['endpoints'][0]['urlParameters']);
  306. $this->assertStringContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  307. $this->generate(['--force' => true]);
  308. $group = Yaml::parseFile($group1FilePath);
  309. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  310. $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
  311. $this->assertStringNotContainsString('Some other useful stuff.', file_get_contents($authFilePath));
  312. }
  313. /** @test */
  314. public function generates_correct_url_params_from_resource_routes_and_field_bindings()
  315. {
  316. RouteFacade::prefix('providers/{provider:slug}')->group(function () {
  317. RouteFacade::resource('users.addresses', TestPartialResourceController::class)->parameters([
  318. 'addresses' => 'address:uuid',
  319. ]);
  320. });
  321. config(['scribe.routes.0.match.prefixes' => ['*']]);
  322. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  323. $this->generate();
  324. $groupA = Yaml::parseFile('.scribe/endpoints/00.yaml');
  325. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses', $groupA['endpoints'][0]['uri']);
  326. $groupB = Yaml::parseFile('.scribe/endpoints/01.yaml');
  327. $this->assertEquals('providers/{provider_slug}/users/{user_id}/addresses/{uuid}', $groupB['endpoints'][0]['uri']);
  328. }
  329. /** @test */
  330. public function generates_correct_url_params_from_resource_routes_and_model_binding()
  331. {
  332. RouteFacade::resource('posts', TestPostController::class)->only('update');
  333. RouteFacade::resource('posts.users', TestPostUserController::class)->only('update');
  334. config(['scribe.routes.0.match.prefixes' => ['*']]);
  335. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  336. $this->generate();
  337. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  338. $this->assertEquals('posts/{slug}', $group['endpoints'][0]['uri']);
  339. $this->assertEquals('posts/{post_slug}/users/{id}', $group['endpoints'][1]['uri']);
  340. }
  341. /** @test */
  342. public function generates_correct_url_params_from_resource_routes_and_model_binding_with_bound_interfaces()
  343. {
  344. $this->app->bind(TestPostBoundInterface::class, fn() => new TestPost());
  345. RouteFacade::resource('posts', TestPostBoundInterfaceController::class)->only('update');
  346. config(['scribe.routes.0.match.prefixes' => ['*']]);
  347. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  348. $this->generate();
  349. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  350. $this->assertEquals('posts/{slug}', $group['endpoints'][0]['uri']);
  351. }
  352. /** @test */
  353. public function generates_correct_url_params_from_non_resource_routes_and_model_binding()
  354. {
  355. RouteFacade::get('posts/{post}/users', function (TestPost $post) {
  356. });
  357. config(['scribe.routes.0.match.prefixes' => ['*']]);
  358. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  359. $this->generate();
  360. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  361. $this->assertEquals('posts/{post_slug}/users', $group['endpoints'][0]['uri']);
  362. }
  363. /** @test */
  364. public function generates_from_camel_dir_if_noExtraction_flag_is_set()
  365. {
  366. config(['scribe.routes.0.exclude' => ['*']]);
  367. Utils::copyDirectory(__DIR__ . '/../Fixtures/.scribe', '.scribe');
  368. $output = $this->generate(['--no-extraction' => true]);
  369. $this->assertStringNotContainsString("Processing route", $output);
  370. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  371. [$intro, $auth] = $crawler->filter('h1 + p')->getIterator();
  372. $this->assertEquals('Heyaa introduction!👋', trim($intro->firstChild->textContent));
  373. $this->assertEquals('This is just a test.', trim($auth->firstChild->textContent));
  374. $group = $crawler->filter('h1')->getNode(2);
  375. $this->assertEquals('General', trim($group->textContent));
  376. $expectedEndpoint = $crawler->filter('h2');
  377. $this->assertCount(1, $expectedEndpoint);
  378. $this->assertEquals("Healthcheck", $expectedEndpoint->text());
  379. }
  380. /** @test */
  381. public function merges_and_correctly_sorts_user_defined_endpoints()
  382. {
  383. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  384. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  385. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  386. if (!is_dir('.scribe/endpoints'))
  387. mkdir('.scribe/endpoints', 0777, true);
  388. copy(__DIR__ . '/../Fixtures/custom.0.yaml', '.scribe/endpoints/custom.0.yaml');
  389. $this->generate();
  390. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  391. $headings = $crawler->filter('h1')->getIterator();
  392. // There should only be six headings — intro, auth and four groups
  393. $this->assertCount(6, $headings);
  394. [$_, $_, $group1, $group2, $group3, $group4] = $headings;
  395. $this->assertEquals('1. Group 1', trim($group1->textContent));
  396. $this->assertEquals('5. Group 5', trim($group2->textContent));
  397. $this->assertEquals('4. Group 4', trim($group3->textContent));
  398. $this->assertEquals('2. Group 2', trim($group4->textContent));
  399. $expectedEndpoints = $crawler->filter('h2');
  400. $this->assertEquals(6, $expectedEndpoints->count());
  401. // Enforce the order of the endpoints
  402. // Ideally, we should also check the groups they're under
  403. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(0)->textContent);
  404. $this->assertEquals("User defined", $expectedEndpoints->getNode(1)->textContent);
  405. $this->assertEquals("GET withBeforeGroup", $expectedEndpoints->getNode(2)->textContent);
  406. $this->assertEquals("GET belongingToAnEarlierBeforeGroup", $expectedEndpoints->getNode(3)->textContent);
  407. $this->assertEquals("GET withAfterGroup", $expectedEndpoints->getNode(4)->textContent);
  408. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(5)->textContent);
  409. }
  410. /** @test */
  411. public function respects_endpoints_and_group_sort_order()
  412. {
  413. RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
  414. RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
  415. RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
  416. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  417. $this->generate();
  418. // First: verify the current order of the groups and endpoints
  419. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  420. $h1s = $crawler->filter('h1');
  421. $this->assertEquals('1. Group 1', trim($h1s->getNode(2)->textContent));
  422. $this->assertEquals('2. Group 2', trim($h1s->getNode(3)->textContent));
  423. $expectedEndpoints = $crawler->filter('h2');
  424. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(0)->textContent);
  425. $this->assertEquals("Another endpoint.", $expectedEndpoints->getNode(1)->textContent);
  426. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(2)->textContent);
  427. // Now swap the endpoints
  428. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  429. $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
  430. $this->assertEquals('api/action1b', $group['endpoints'][1]['uri']);
  431. $action1 = $group['endpoints'][0];
  432. $group['endpoints'][0] = $group['endpoints'][1];
  433. $group['endpoints'][1] = $action1;
  434. file_put_contents('.scribe/endpoints/00.yaml', Yaml::dump(
  435. $group, 20, 2,
  436. Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE | Yaml::DUMP_OBJECT_AS_MAP
  437. ));
  438. // And then the groups
  439. rename('.scribe/endpoints/00.yaml', '.scribe/endpoints/temp.yaml');
  440. rename('.scribe/endpoints/01.yaml', '.scribe/endpoints/00.yaml');
  441. rename('.scribe/endpoints/temp.yaml', '.scribe/endpoints/1.yaml');
  442. $this->generate();
  443. $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
  444. $h1s = $crawler->filter('h1');
  445. $this->assertEquals('2. Group 2', trim($h1s->getNode(2)->textContent));
  446. $this->assertEquals('1. Group 1', trim($h1s->getNode(3)->textContent));
  447. $expectedEndpoints = $crawler->filter('h2');
  448. $this->assertEquals("GET api/action2", $expectedEndpoints->getNode(0)->textContent);
  449. $this->assertEquals("Another endpoint.", $expectedEndpoints->getNode(1)->textContent);
  450. $this->assertEquals("Some endpoint.", $expectedEndpoints->getNode(2)->textContent);
  451. }
  452. /** @test */
  453. public function will_auto_set_content_type_to_multipart_if_file_params_are_present()
  454. {
  455. /**
  456. * @bodyParam param string required
  457. */
  458. RouteFacade::post('no-file', fn() => null);
  459. /**
  460. * @bodyParam a_file file required
  461. */
  462. RouteFacade::post('top-level-file', fn() => null);
  463. /**
  464. * @bodyParam data object
  465. * @bodyParam data.thing string
  466. * @bodyParam data.a_file file
  467. */
  468. RouteFacade::post('nested-file', fn() => null);
  469. config(['scribe.routes.0.match.prefixes' => ['*']]);
  470. config(['scribe.routes.0.apply.response_calls.methods' => []]);
  471. $this->generate();
  472. $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
  473. $this->assertEquals('no-file', $group['endpoints'][0]['uri']);
  474. $this->assertEquals('application/json', $group['endpoints'][0]['headers']['Content-Type']);
  475. $this->assertEquals('top-level-file', $group['endpoints'][1]['uri']);
  476. $this->assertEquals('multipart/form-data', $group['endpoints'][1]['headers']['Content-Type']);
  477. $this->assertEquals('nested-file', $group['endpoints'][2]['uri']);
  478. $this->assertEquals('multipart/form-data', $group['endpoints'][2]['headers']['Content-Type']);
  479. }
  480. protected function postmanOutputPath(bool $laravelType = false): string
  481. {
  482. return $laravelType
  483. ? Storage::disk('local')->path('scribe/collection.json') : 'public/docs/collection.json';
  484. }
  485. protected function openapiOutputPath(bool $laravelType = false): string
  486. {
  487. return $laravelType
  488. ? Storage::disk('local')->path('scribe/openapi.yaml') : 'public/docs/openapi.yaml';
  489. }
  490. protected function htmlOutputPath(): string
  491. {
  492. return 'public/docs/index.html';
  493. }
  494. protected function bladeOutputPath(): string
  495. {
  496. return View::getFinder()->find('scribe/index');
  497. }
  498. }