PostmanCollectionWriter.php 14 KB

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