PostmanCollectionWriter.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. <?php
  2. namespace Knuckles\Scribe\Writing;
  3. use Illuminate\Support\Collection;
  4. use Illuminate\Support\Facades\URL;
  5. use Illuminate\Support\Str;
  6. use Knuckles\Scribe\Tools\DocumentationConfig;
  7. use Ramsey\Uuid\Uuid;
  8. use ReflectionMethod;
  9. class PostmanCollectionWriter
  10. {
  11. /**
  12. * Postman collection schema version
  13. */
  14. const VERSION = '2.1.0';
  15. /**
  16. * @var DocumentationConfig
  17. */
  18. protected $config;
  19. protected $baseUrl;
  20. public function __construct(DocumentationConfig $config = null)
  21. {
  22. $this->config = $config ?: new DocumentationConfig(config('scribe', []));
  23. $this->baseUrl = ($this->config->get('postman.base_url') ?: $this->config->get('base_url')) ?: config('app.url');
  24. }
  25. public function generatePostmanCollection(Collection $groupedEndpoints)
  26. {
  27. $collection = [
  28. 'variable' => [
  29. [
  30. 'id' => 'baseUrl',
  31. 'key' => 'baseUrl',
  32. 'type' => 'string',
  33. 'name' => 'string',
  34. 'value' => parse_url($this->baseUrl, PHP_URL_HOST) ?: $this->baseUrl, // if there's no protocol, parse_url might fail
  35. ],
  36. ],
  37. 'info' => [
  38. 'name' => $this->config->get('title') ?: config('app.name'),
  39. '_postman_id' => Uuid::uuid4()->toString(),
  40. 'description' => $this->config->get('description', ''),
  41. 'schema' => "https://schema.getpostman.com/json/collection/v" . self::VERSION . "/collection.json",
  42. ],
  43. 'item' => $groupedEndpoints->map(function (Collection $routes, $groupName) {
  44. return [
  45. 'name' => $groupName,
  46. 'description' => $routes->first()['metadata']['groupDescription'],
  47. 'item' => $routes->map(\Closure::fromCallable([$this, 'generateEndpointItem']))->toArray(),
  48. ];
  49. })->values()->toArray(),
  50. 'auth' => $this->generateAuthObject(),
  51. ];
  52. return $collection;
  53. }
  54. protected function generateAuthObject()
  55. {
  56. if (!$this->config->get('auth.enabled')) {
  57. return [
  58. 'type' => 'noauth',
  59. ];
  60. }
  61. switch ($this->config->get('auth.in')) {
  62. case "basic":
  63. return [
  64. 'type' => 'basic',
  65. ];
  66. case "bearer":
  67. return [
  68. 'type' => 'bearer',
  69. ];
  70. default:
  71. return [
  72. 'type' => 'apikey',
  73. 'apikey' => [
  74. [
  75. 'key' => 'in',
  76. 'value' => $this->config->get('auth.in'),
  77. 'type' => 'string',
  78. ],
  79. [
  80. 'key' => 'key',
  81. 'value' => $this->config->get('auth.name'),
  82. 'type' => 'string',
  83. ],
  84. ],
  85. ];
  86. }
  87. }
  88. protected function generateEndpointItem($endpoint): array
  89. {
  90. $endpointItem = [
  91. 'name' => $endpoint['metadata']['title'] !== '' ? $endpoint['metadata']['title'] : $endpoint['uri'],
  92. 'request' => [
  93. 'url' => $this->generateUrlObject($endpoint),
  94. 'method' => $endpoint['methods'][0],
  95. 'header' => $this->resolveHeadersForEndpoint($endpoint),
  96. 'body' => empty($endpoint['bodyParameters']) ? null : $this->getBodyData($endpoint),
  97. 'description' => $endpoint['metadata']['description'] ?? null,
  98. ],
  99. 'response' => [],
  100. ];
  101. if (($endpoint['metadata']['authenticated'] ?? false) === false) {
  102. $endpointItem['request']['auth'] = ['type' => 'noauth'];
  103. }
  104. return $endpointItem;
  105. }
  106. protected function getBodyData(array $endpoint): array
  107. {
  108. $body = [];
  109. $contentType = $endpoint['headers']['Content-Type'] ?? null;
  110. switch ($contentType) {
  111. case 'multipart/form-data':
  112. $inputMode = 'formdata';
  113. break;
  114. case 'application/json':
  115. default:
  116. $inputMode = 'raw';
  117. }
  118. $body['mode'] = $inputMode;
  119. $body[$inputMode] = [];
  120. switch ($inputMode) {
  121. case 'formdata':
  122. foreach ($endpoint['cleanBodyParameters'] as $key => $value) {
  123. $params = [
  124. 'key' => $key,
  125. 'value' => $value,
  126. 'type' => 'text',
  127. ];
  128. $body[$inputMode][] = $params;
  129. }
  130. foreach ($endpoint['fileParameters'] as $key => $value) {
  131. while (is_array($value)) { // For arrays of files, just send the first one
  132. $key .= '[]';
  133. $value = $value[0];
  134. }
  135. $params = [
  136. 'key' => $key,
  137. 'src' => [],
  138. 'type' => 'file',
  139. ];
  140. $body[$inputMode][] = $params;
  141. }
  142. break;
  143. case 'raw':
  144. default:
  145. $body[$inputMode] = json_encode($endpoint['cleanBodyParameters'], JSON_PRETTY_PRINT);
  146. }
  147. return $body;
  148. }
  149. protected function resolveHeadersForEndpoint($route)
  150. {
  151. [$where, $authParam] = $this->getAuthParamToExclude();
  152. $headers = collect($route['headers']);
  153. if ($where === 'header') {
  154. unset($headers[$authParam]);
  155. }
  156. $headers = $headers
  157. ->union([
  158. 'Accept' => 'application/json',
  159. ])
  160. ->map(function ($value, $header) {
  161. // Allow users to write ['header' => '@{{value}}'] in config
  162. // and have it rendered properly as {{value}} in the Postman collection.
  163. $value = str_replace('@{{', '{{', $value);
  164. return [
  165. 'key' => $header,
  166. 'value' => $value,
  167. ];
  168. })
  169. ->values()
  170. ->all();
  171. return $headers;
  172. }
  173. protected function generateUrlObject($route)
  174. {
  175. $base = [
  176. 'protocol' => Str::startsWith($this->baseUrl, 'https') ? 'https' : 'http',
  177. 'host' => '{{baseUrl}}',
  178. // Change laravel/symfony URL params ({example}) to Postman style, prefixed with a colon
  179. 'path' => preg_replace_callback('/\{(\w+)\??}/', function ($matches) {
  180. return ':' . $matches[1];
  181. }, $route['uri']),
  182. ];
  183. $query = [];
  184. [$where, $authParam] = $this->getAuthParamToExclude();
  185. foreach ($route['queryParameters'] ?? [] as $name => $parameterData) {
  186. if ($where === 'query' && $authParam === $name) {
  187. continue;
  188. }
  189. if (Str::endsWith($parameterData['type'], '[]') || $parameterData['type'] === 'object') {
  190. $values = empty($parameterData['value']) ? [] : $parameterData['value'];
  191. foreach ($values as $index => $value) {
  192. // PHP's parse_str supports array query parameters as filters[0]=name&filters[1]=age OR filters[]=name&filters[]=age
  193. // Going with the first to also support object query parameters
  194. // See https://www.php.net/manual/en/function.parse-str.php
  195. $query[] = [
  196. 'key' => urlencode("{$name}[$index]"),
  197. 'value' => urlencode($value),
  198. 'description' => strip_tags($parameterData['description']),
  199. // Default query params to disabled if they aren't required and have empty values
  200. 'disabled' => !($parameterData['required'] ?? false) && empty($parameterData['value']),
  201. ];
  202. }
  203. } else {
  204. $query[] = [
  205. 'key' => urlencode($name),
  206. 'value' => urlencode($parameterData['value']),
  207. 'description' => strip_tags($parameterData['description']),
  208. // Default query params to disabled if they aren't required and have empty values
  209. 'disabled' => !($parameterData['required'] ?? false) && empty($parameterData['value']),
  210. ];
  211. }
  212. }
  213. $base['query'] = $query;
  214. // Create raw url-parameter (Insomnia uses this on import)
  215. $queryString = collect($base['query'] ?? [])->map(function ($queryParamData) {
  216. return $queryParamData['key'] . '=' . $queryParamData['value'];
  217. })->implode('&');
  218. $base['raw'] = sprintf('%s://%s/%s%s',
  219. $base['protocol'], $base['host'], $base['path'], $queryString ? "?{$queryString}" : null
  220. );
  221. $urlParams = collect($route['urlParameters']);
  222. if ($urlParams->isEmpty()) {
  223. return $base;
  224. }
  225. $base['variable'] = $urlParams->map(function ($parameter, $name) {
  226. return [
  227. 'id' => $name,
  228. 'key' => $name,
  229. 'value' => urlencode($parameter['value']),
  230. 'description' => $parameter['description'],
  231. ];
  232. })->values()->toArray();
  233. return $base;
  234. }
  235. private function getAuthParamToExclude(): array
  236. {
  237. if (!$this->config->get('auth.enabled')) {
  238. return [null, null];
  239. }
  240. if (in_array($this->config->get('auth.in'), ['bearer', 'basic'])) {
  241. return ['header', 'Authorization'];
  242. } else {
  243. return [$this->config->get('auth.in'), $this->config->get('auth.name')];
  244. }
  245. }
  246. }