GenerateDocumentationTest.php 26 KB

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