PostmanCollectionWriter.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. <?php
  2. namespace Knuckles\Scribe\Writing;
  3. use Illuminate\Support\Str;
  4. use Knuckles\Camel\Extraction\Response;
  5. use Knuckles\Camel\Output\OutputEndpointData;
  6. use Knuckles\Camel\Output\Parameter;
  7. use Knuckles\Scribe\Tools\DocumentationConfig;
  8. use Ramsey\Uuid\Uuid;
  9. class PostmanCollectionWriter
  10. {
  11. /**
  12. * Postman collection schema version
  13. * https://schema.getpostman.com/json/collection/v2.1.0/collection.json
  14. */
  15. const SPEC_VERSION = '2.1.0';
  16. protected DocumentationConfig $config;
  17. protected string $baseUrl;
  18. public function __construct(?DocumentationConfig $config = null)
  19. {
  20. $this->config = $config ?: new DocumentationConfig(config('scribe', []));
  21. $this->baseUrl = $this->config->get('base_url') ?: config('app.url');
  22. }
  23. /**
  24. * @param array[] $groupedEndpoints
  25. *
  26. * @return array
  27. */
  28. public function generatePostmanCollection(array $groupedEndpoints): array
  29. {
  30. $collection = [
  31. 'variable' => [
  32. [
  33. 'id' => 'baseUrl',
  34. 'key' => 'baseUrl',
  35. 'type' => 'string',
  36. 'name' => 'string',
  37. 'value' => $this->baseUrl,
  38. ],
  39. ],
  40. 'info' => [
  41. 'name' => $this->config->get('title') ?: config('app.name'),
  42. '_postman_id' => Uuid::uuid4()->toString(),
  43. 'description' => $this->config->get('description', ''),
  44. 'schema' => "https://schema.getpostman.com/json/collection/v" . self::SPEC_VERSION . "/collection.json",
  45. ],
  46. 'item' => array_values(array_map(function (array $group) {
  47. return [
  48. 'name' => $group['name'],
  49. 'description' => $group['description'],
  50. 'item' => $this->generateSubItem($group),
  51. ];
  52. }, $groupedEndpoints)),
  53. 'auth' => $this->generateAuthObject(),
  54. ];
  55. return $collection;
  56. }
  57. protected function generateAuthObject(): array
  58. {
  59. if (!$this->config->get('auth.enabled')) {
  60. return [
  61. 'type' => 'noauth',
  62. ];
  63. }
  64. return match ($this->config->get('auth.in')) {
  65. "basic" => [
  66. 'type' => 'basic',
  67. ],
  68. "bearer" => [
  69. 'type' => 'bearer',
  70. 'bearer' => [
  71. [
  72. 'key' => $this->config->get('auth.name'),
  73. 'type' => 'string',
  74. ],
  75. ],
  76. ],
  77. default => [
  78. 'type' => 'apikey',
  79. 'apikey' => [
  80. [
  81. 'key' => 'in',
  82. 'value' => $this->config->get('auth.in'),
  83. 'type' => 'string',
  84. ],
  85. [
  86. 'key' => 'key',
  87. 'value' => $this->config->get('auth.name'),
  88. 'type' => 'string',
  89. ],
  90. ],
  91. ],
  92. };
  93. }
  94. protected function generateSubItem(array $group): array
  95. {
  96. $seenSubgroups = [];
  97. $items = [];
  98. /** @var OutputEndpointData $endpoint */
  99. foreach ($group['endpoints'] as $endpoint) {
  100. if (!$endpoint->metadata->subgroup) {
  101. $items[] = $this->generateEndpointItem($endpoint);
  102. } else {
  103. if (isset($seenSubgroups[$endpoint->metadata->subgroup])) {
  104. $subgroupIndex = $seenSubgroups[$endpoint->metadata->subgroup];
  105. $items[$subgroupIndex]['description'] = $items[$subgroupIndex]['description'] ?: $endpoint->metadata->subgroupDescription;
  106. $items[$subgroupIndex]['item'] = [...$items[$subgroupIndex]['item'], $this->generateEndpointItem($endpoint)];
  107. } else {
  108. $items[] = [
  109. 'name' => $endpoint->metadata->subgroup,
  110. 'description' => $endpoint->metadata->subgroupDescription,
  111. 'item' => [$this->generateEndpointItem($endpoint)],
  112. ];
  113. $seenSubgroups[$endpoint->metadata->subgroup] = count($items) - 1;
  114. }
  115. }
  116. }
  117. return $items;
  118. }
  119. protected function generateEndpointItem(OutputEndpointData $endpoint): array
  120. {
  121. $method = $endpoint->httpMethods[0];
  122. $bodyParameters = empty($endpoint->bodyParameters) ? null : $this->getBodyData($endpoint);
  123. if ((in_array('PUT', $endpoint->httpMethods) || in_array('PATCH', $endpoint->httpMethods))
  124. && isset($bodyParameters['formdata'])) {
  125. $method = 'POST';
  126. $bodyParameters['formdata'][] = [
  127. 'key' => '_method',
  128. 'value' => $endpoint->httpMethods[0],
  129. 'type' => 'text',
  130. ];
  131. }
  132. $endpointItem = [
  133. 'name' => $endpoint->metadata->title !== '' ? $endpoint->metadata->title : ($endpoint->httpMethods[0].' '.$endpoint->uri),
  134. 'request' => [
  135. 'url' => $this->generateUrlObject($endpoint),
  136. 'method' => $method,
  137. 'header' => $this->resolveHeadersForEndpoint($endpoint),
  138. 'body' => $bodyParameters,
  139. 'description' => $endpoint->metadata->description,
  140. ],
  141. 'response' => $this->getResponses($endpoint),
  142. ];
  143. if ($endpoint->metadata->authenticated === false) {
  144. $endpointItem['request']['auth'] = ['type' => 'noauth'];
  145. }
  146. return $endpointItem;
  147. }
  148. protected function getBodyData(OutputEndpointData $endpoint): array
  149. {
  150. $body = [];
  151. $contentType = $endpoint->headers['Content-Type'] ?? null;
  152. $inputMode = match ($contentType) {
  153. 'multipart/form-data' => 'formdata',
  154. 'application/x-www-form-urlencoded' => 'urlencoded',
  155. default => 'raw',
  156. };
  157. $body['mode'] = $inputMode;
  158. $body[$inputMode] = [];
  159. switch ($inputMode) {
  160. case 'formdata':
  161. case 'urlencoded':
  162. $body[$inputMode] = $this->getFormDataParams(
  163. $endpoint->cleanBodyParameters, null, $endpoint->bodyParameters
  164. );
  165. foreach ($endpoint->fileParameters as $key => $value) {
  166. while (is_array($value)) {
  167. $keys = array_keys($value);
  168. if ($keys[0] === 0) {
  169. // List of files
  170. $key .= '[]';
  171. $value = $value[0];
  172. } else {
  173. $key .= '['.$keys[0].']';
  174. $value = $value[$keys[0]];
  175. }
  176. }
  177. $params = [
  178. 'key' => $key,
  179. 'src' => [],
  180. 'type' => 'file',
  181. ];
  182. $body[$inputMode][] = $params;
  183. }
  184. break;
  185. case 'raw':
  186. default:
  187. $body[$inputMode] = json_encode($endpoint->cleanBodyParameters, JSON_UNESCAPED_UNICODE);
  188. }
  189. return $body;
  190. }
  191. /**
  192. * Format form-data parameters correctly for arrays eg. data[item][index] = value
  193. */
  194. protected function getFormDataParams(array $paramsKeyValue, ?string $key = null, array $paramsFullDetails = []): array
  195. {
  196. $body = [];
  197. foreach ($paramsKeyValue as $index => $value) {
  198. $index = $key ? ($key . '[' . $index . ']') : $index;
  199. if (!is_array($value)) {
  200. $body[] = [
  201. 'key' => $index,
  202. 'value' => $value,
  203. 'type' => 'text',
  204. 'description' => $paramsFullDetails[$index]->description ?? '',
  205. ];
  206. continue;
  207. }
  208. $body = array_merge($body, $this->getFormDataParams($value, $index));
  209. }
  210. return $body;
  211. }
  212. protected function resolveHeadersForEndpoint(OutputEndpointData $endpointData): array
  213. {
  214. [$where, $authParam] = $this->getAuthParamToExclude();
  215. $headers = collect($endpointData->headers);
  216. if ($where === 'header') {
  217. unset($headers[$authParam]);
  218. }
  219. $headers = $headers
  220. ->union([
  221. 'Accept' => 'application/json',
  222. ])
  223. ->map(function ($value, $header) {
  224. // Allow users to write ['header' => '@{{value}}'] in config
  225. // and have it rendered properly as {{value}} in the Postman collection.
  226. $value = str_replace('@{{', '{{', $value);
  227. return [
  228. 'key' => $header,
  229. 'value' => $value,
  230. ];
  231. })
  232. ->values()
  233. ->all();
  234. return $headers;
  235. }
  236. protected function generateUrlObject(OutputEndpointData $endpointData): array
  237. {
  238. $base = [
  239. 'host' => '{{baseUrl}}',
  240. // Change laravel/symfony URL params ({example}) to Postman style, prefixed with a colon
  241. 'path' => preg_replace_callback('/\{(\w+)\??}/', function ($matches) {
  242. return ':' . $matches[1];
  243. }, $endpointData->uri),
  244. ];
  245. $query = [];
  246. [$where, $authParam] = $this->getAuthParamToExclude();
  247. /**
  248. * @var string $name
  249. * @var Parameter $parameterData
  250. */
  251. foreach ($endpointData->queryParameters as $name => $parameterData) {
  252. if ($where === 'query' && $authParam === $name) {
  253. continue;
  254. }
  255. if (Str::endsWith($parameterData->type, '[]') || $parameterData->type === 'object') {
  256. $values = empty($parameterData->example) ? [] : $parameterData->example;
  257. foreach ($values as $index => $value) {
  258. // PHP's parse_str supports array query parameters as filters[0]=name&filters[1]=age OR filters[]=name&filters[]=age
  259. // Going with the first to also support object query parameters
  260. // See https://www.php.net/manual/en/function.parse-str.php
  261. $query[] = [
  262. 'key' => "{$name}[$index]",
  263. 'value' => is_string($value) ? $value : strval($value),
  264. 'description' => strip_tags($parameterData->description),
  265. // Default query params to disabled if they aren't required and have empty values
  266. 'disabled' => !$parameterData->required && empty($parameterData->example),
  267. ];
  268. }
  269. // If there are no values, add one entry so the parameter shows up in the Postman UI.
  270. if (empty($values)) {
  271. $query[] = [
  272. 'key' => "{$name}[]",
  273. 'value' => '',
  274. 'description' => strip_tags($parameterData->description),
  275. // Default query params to disabled if they aren't required and have empty values
  276. 'disabled' => true,
  277. ];
  278. }
  279. } else {
  280. $query[] = [
  281. 'key' => urlencode($name),
  282. 'value' => $parameterData->example != null ? urlencode($parameterData->example) : '',
  283. 'description' => strip_tags($parameterData->description),
  284. // Default query params to disabled if they aren't required and have empty values
  285. 'disabled' => !$parameterData->required && empty($parameterData->example),
  286. ];
  287. }
  288. }
  289. $base['query'] = $query;
  290. // Create raw url-parameter (Insomnia uses this on import)
  291. $queryString = collect($base['query'])->map(function ($queryParamData) {
  292. return $queryParamData['key'] . '=' . $queryParamData['value'];
  293. })->implode('&');
  294. $base['raw'] = sprintf('%s/%s%s', $base['host'], $base['path'], $queryString ? "?{$queryString}" : null);
  295. $urlParams = collect($endpointData->urlParameters);
  296. if ($urlParams->isEmpty()) {
  297. return $base;
  298. }
  299. $base['variable'] = $urlParams->map(function (Parameter $parameter, $name) {
  300. return [
  301. 'id' => $name,
  302. 'key' => $name,
  303. 'value' => urlencode($parameter->example),
  304. 'description' => $parameter->description,
  305. ];
  306. })->values()->toArray();
  307. return $base;
  308. }
  309. private function getAuthParamToExclude(): array
  310. {
  311. if (!$this->config->get('auth.enabled')) {
  312. return [null, null];
  313. }
  314. if (in_array($this->config->get('auth.in'), ['bearer', 'basic'])) {
  315. return ['header', 'Authorization'];
  316. } else {
  317. return [$this->config->get('auth.in'), $this->config->get('auth.name')];
  318. }
  319. }
  320. private function getResponses(OutputEndpointData $endpoint): array
  321. {
  322. return collect($endpoint->responses)->map(function (Response $response) {
  323. $headers = [];
  324. foreach ($response->headers as $header => $value) {
  325. $headers[] = [
  326. 'key' => $header,
  327. 'value' => $value,
  328. ];
  329. }
  330. return [
  331. 'header' => $headers,
  332. 'code' => $response->status,
  333. 'body' => $response->content,
  334. 'name' => $this->getResponseDescription($response),
  335. ];
  336. })->toArray();
  337. }
  338. protected function getResponseDescription(Response $response): string
  339. {
  340. if (Str::startsWith($response->content, "<<binary>>")) {
  341. return trim(str_replace("<<binary>>", "", $response->content));
  342. }
  343. $description = strval($response->description);
  344. // Don't include the status code in description; see https://github.com/knuckleswtf/scribe/issues/271
  345. if (preg_match("/\d{3},\s+(.+)/", $description, $matches)) {
  346. $description = $matches[1];
  347. } else if ($description === strval($response->status)) {
  348. $description = '';
  349. }
  350. return $description;
  351. }
  352. }