Generator.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. namespace Knuckles\Scribe\Extracting;
  3. use Faker\Factory;
  4. use Illuminate\Http\UploadedFile;
  5. use Illuminate\Routing\Route;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Str;
  8. use Knuckles\Scribe\Extracting\Strategies\Strategy;
  9. use Knuckles\Scribe\Tools\DocumentationConfig;
  10. use Knuckles\Scribe\Tools\ConsoleOutputUtils as c;
  11. use Knuckles\Scribe\Tools\Utils as u;
  12. use ReflectionClass;
  13. use ReflectionFunctionAbstract;
  14. class Generator
  15. {
  16. /**
  17. * @var DocumentationConfig
  18. */
  19. private $config;
  20. /**
  21. * @var Route|null
  22. */
  23. private static $routeBeingProcessed = null;
  24. public function __construct(DocumentationConfig $config = null)
  25. {
  26. // If no config is injected, pull from global
  27. $this->config = $config ?: new DocumentationConfig(config('scribe'));
  28. }
  29. /**
  30. * External interface that allows users to know what route is currently being processed
  31. */
  32. public static function getRouteBeingProcessed(): ?Route
  33. {
  34. return self::$routeBeingProcessed;
  35. }
  36. /**
  37. * @param Route $route
  38. *
  39. * @return mixed
  40. */
  41. public function getUri(Route $route)
  42. {
  43. return $route->uri();
  44. }
  45. /**
  46. * @param Route $route
  47. *
  48. * @return mixed
  49. */
  50. public function getMethods(Route $route)
  51. {
  52. $methods = $route->methods();
  53. // Laravel adds an automatic "HEAD" endpoint for each GET request, so we'll strip that out,
  54. // but not if there's only one method (means it was intentional)
  55. if (count($methods) === 1) {
  56. return $methods;
  57. }
  58. return array_diff($methods, ['HEAD']);
  59. }
  60. /**
  61. * @param \Illuminate\Routing\Route $route
  62. * @param array $routeRules Rules to apply when generating documentation for this route
  63. *
  64. * @return array
  65. * @throws \ReflectionException
  66. *
  67. */
  68. public function processRoute(Route $route, array $routeRules = [])
  69. {
  70. self::$routeBeingProcessed = $route;
  71. [$controllerName, $methodName] = u::getRouteClassAndMethodNames($route);
  72. $controller = new ReflectionClass($controllerName);
  73. $method = u::getReflectedRouteMethod([$controllerName, $methodName]);
  74. $parsedRoute = [
  75. 'id' => md5($this->getUri($route) . ':' . implode($this->getMethods($route))),
  76. 'methods' => $this->getMethods($route),
  77. 'uri' => $this->getUri($route),
  78. ];
  79. $metadata = $this->fetchMetadata($controller, $method, $route, $routeRules, $parsedRoute);
  80. $parsedRoute['metadata'] = $metadata;
  81. $urlParameters = $this->fetchUrlParameters($controller, $method, $route, $routeRules, $parsedRoute);
  82. $parsedRoute['urlParameters'] = $urlParameters;
  83. $parsedRoute['cleanUrlParameters'] = self::cleanParams($urlParameters);
  84. $parsedRoute['boundUri'] = u::getUrlWithBoundParameters($route, $parsedRoute['cleanUrlParameters']);
  85. $parsedRoute = $this->addAuthField($parsedRoute);
  86. $queryParameters = $this->fetchQueryParameters($controller, $method, $route, $routeRules, $parsedRoute);
  87. $parsedRoute['queryParameters'] = $queryParameters;
  88. $parsedRoute['cleanQueryParameters'] = self::cleanParams($queryParameters);
  89. $headers = $this->fetchRequestHeaders($controller, $method, $route, $routeRules, $parsedRoute);
  90. $parsedRoute['headers'] = $headers;
  91. $bodyParameters = $this->fetchBodyParameters($controller, $method, $route, $routeRules, $parsedRoute);
  92. $parsedRoute['bodyParameters'] = $bodyParameters;
  93. $parsedRoute['cleanBodyParameters'] = self::cleanParams($bodyParameters);
  94. if (count($parsedRoute['cleanBodyParameters']) && !isset($parsedRoute['headers']['Content-Type'])) {
  95. // Set content type if the user forgot to set it
  96. $parsedRoute['headers']['Content-Type'] = 'application/json';
  97. }
  98. [$files, $regularParameters] = collect($parsedRoute['cleanBodyParameters'])->partition(function ($example) {
  99. return $example instanceof UploadedFile;
  100. });
  101. if (count($files)) {
  102. $parsedRoute['headers']['Content-Type'] = 'multipart/form-data';
  103. }
  104. $parsedRoute['fileParameters'] = $files->toArray();
  105. $parsedRoute['cleanBodyParameters'] = $regularParameters->toArray();
  106. $responses = $this->fetchResponses($controller, $method, $route, $routeRules, $parsedRoute);
  107. $parsedRoute['responses'] = $responses;
  108. $parsedRoute['showresponse'] = !empty($responses);
  109. $responseFields = $this->fetchResponseFields($controller, $method, $route, $routeRules, $parsedRoute);
  110. $parsedRoute['responseFields'] = $responseFields;
  111. $parsedRoute['nestedBodyParameters'] = $this->nestArrayAndObjectFields($parsedRoute['bodyParameters']);
  112. self::$routeBeingProcessed = null;
  113. return $parsedRoute;
  114. }
  115. protected function fetchMetadata(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  116. {
  117. $context['metadata'] = [
  118. 'groupName' => $this->config->get('default_group', ''),
  119. 'groupDescription' => '',
  120. 'title' => '',
  121. 'description' => '',
  122. 'authenticated' => false,
  123. ];
  124. return $this->iterateThroughStrategies('metadata', $context, [$route, $controller, $method, $rulesToApply]);
  125. }
  126. protected function fetchUrlParameters(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  127. {
  128. return $this->iterateThroughStrategies('urlParameters', $context, [$route, $controller, $method, $rulesToApply]);
  129. }
  130. protected function fetchQueryParameters(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  131. {
  132. return $this->iterateThroughStrategies('queryParameters', $context, [$route, $controller, $method, $rulesToApply]);
  133. }
  134. protected function fetchBodyParameters(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  135. {
  136. return $this->iterateThroughStrategies('bodyParameters', $context, [$route, $controller, $method, $rulesToApply]);
  137. }
  138. protected function fetchResponses(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  139. {
  140. $responses = $this->iterateThroughStrategies('responses', $context, [$route, $controller, $method, $rulesToApply]);
  141. if (count($responses)) {
  142. return array_filter($responses, function ($response) {
  143. return $response['content'] != null;
  144. });
  145. }
  146. return [];
  147. }
  148. protected function fetchResponseFields(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  149. {
  150. return $this->iterateThroughStrategies('responseFields', $context, [$route, $controller, $method, $rulesToApply]);
  151. }
  152. protected function fetchRequestHeaders(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  153. {
  154. $headers = $this->iterateThroughStrategies('headers', $context, [$route, $controller, $method, $rulesToApply]);
  155. return array_filter($headers);
  156. }
  157. protected function iterateThroughStrategies(string $stage, array $extractedData, array $arguments)
  158. {
  159. $defaultStrategies = [
  160. 'metadata' => [
  161. \Knuckles\Scribe\Extracting\Strategies\Metadata\GetFromDocBlocks::class,
  162. ],
  163. 'urlParameters' => [
  164. \Knuckles\Scribe\Extracting\Strategies\UrlParameters\GetFromLaravelAPI::class,
  165. \Knuckles\Scribe\Extracting\Strategies\UrlParameters\GetFromLumenAPI::class,
  166. \Knuckles\Scribe\Extracting\Strategies\UrlParameters\GetFromUrlParamTag::class,
  167. ],
  168. 'queryParameters' => [
  169. \Knuckles\Scribe\Extracting\Strategies\QueryParameters\GetFromQueryParamTag::class,
  170. ],
  171. 'headers' => [
  172. \Knuckles\Scribe\Extracting\Strategies\Headers\GetFromRouteRules::class,
  173. \Knuckles\Scribe\Extracting\Strategies\Headers\GetFromHeaderTag::class,
  174. ],
  175. 'bodyParameters' => [
  176. \Knuckles\Scribe\Extracting\Strategies\BodyParameters\GetFromFormRequest::class,
  177. \Knuckles\Scribe\Extracting\Strategies\BodyParameters\GetFromBodyParamTag::class,
  178. ],
  179. 'responses' => [
  180. \Knuckles\Scribe\Extracting\Strategies\Responses\UseTransformerTags::class,
  181. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseTag::class,
  182. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseFileTag::class,
  183. \Knuckles\Scribe\Extracting\Strategies\Responses\UseApiResourceTags::class,
  184. \Knuckles\Scribe\Extracting\Strategies\Responses\ResponseCalls::class,
  185. ],
  186. 'responseFields' => [
  187. \Knuckles\Scribe\Extracting\Strategies\ResponseFields\GetFromResponseFieldTag::class,
  188. ],
  189. ];
  190. // Use the default strategies for the stage, unless they were explicitly set
  191. $strategies = $this->config->get("strategies.$stage", $defaultStrategies[$stage]);
  192. $extractedData[$stage] = $extractedData[$stage] ?? [];
  193. foreach ($strategies as $strategyClass) {
  194. /** @var Strategy $strategy */
  195. $strategy = new $strategyClass($this->config);
  196. $strategyArgs = $arguments;
  197. $strategyArgs[] = $extractedData;
  198. $results = $strategy(...$strategyArgs);
  199. if (!is_null($results)) {
  200. foreach ($results as $index => $item) {
  201. if ($stage == 'responses') {
  202. // Responses from different strategies are all added, not overwritten
  203. $extractedData[$stage][] = $item;
  204. continue;
  205. }
  206. // We're using a for loop rather than array_merge or +=
  207. // so it does not renumber numeric keys and also allows values to be overwritten
  208. // Don't allow overwriting if an empty value is trying to replace a set one
  209. if (!in_array($extractedData[$stage], [null, ''], true) && in_array($item, [null, ''], true)) {
  210. continue;
  211. } else {
  212. $extractedData[$stage][$index] = $item;
  213. }
  214. }
  215. }
  216. }
  217. return $extractedData[$stage];
  218. }
  219. /**
  220. * This method prepares and simplifies request parameters for use in example requests and response calls.
  221. * It takes in an array with rich details about a parameter eg
  222. * ['age' => [
  223. * 'description' => 'The age',
  224. * 'value' => 12,
  225. * 'required' => false,
  226. * ]]
  227. * And transforms them into key-example pairs : ['age' => 12]
  228. * It also filters out parameters which have null values and have 'required' as false.
  229. * It converts all file params that have string examples to actual files (instances of UploadedFile).
  230. *
  231. * @param array $parameters
  232. *
  233. * @return array
  234. */
  235. public static function cleanParams(array $parameters): array
  236. {
  237. $cleanParameters = [];
  238. foreach ($parameters as $paramName => $details) {
  239. // Remove params which have no examples and are optional.
  240. if (is_null($details['value']) && $details['required'] === false) {
  241. continue;
  242. }
  243. if (($details['type'] ?? '') === 'file' && is_string($details['value'])) {
  244. $details['value'] = self::convertStringValueToUploadedFileInstance($details['value']);
  245. }
  246. if (Str::contains($paramName, '.')) { // Object field (or array of objects)
  247. self::setObject($cleanParameters, $paramName, $details['value'], $parameters, ($details['required'] ?? false));
  248. } else {
  249. $cleanParameters[$paramName] = $details['value'];
  250. }
  251. }
  252. return $cleanParameters;
  253. }
  254. public static function setObject(array &$results, string $path, $value, array $source, bool $isRequired)
  255. {
  256. $parts = array_reverse(explode('.', $path));
  257. array_shift($parts); // Get rid of the field name
  258. $baseName = join('.', array_reverse($parts));
  259. // The type should be indicated in the source object by now; we don't need it in the name
  260. $normalisedBaseName = Str::replaceLast('[]', '', $baseName);
  261. $parentData = Arr::get($source, $normalisedBaseName);
  262. if ($parentData) {
  263. // Path we use for data_set
  264. $dotPath = str_replace('[]', '.0', $path);
  265. if ($parentData['type'] === 'object') {
  266. if (!Arr::has($results, $dotPath)) {
  267. Arr::set($results, $dotPath, $value);
  268. }
  269. } else if ($parentData['type'] === 'object[]') {
  270. if (!Arr::has($results, $dotPath)) {
  271. Arr::set($results, $dotPath, $value);
  272. }
  273. // If there's a second item in the array, set for that too.
  274. if ($value !== null && Arr::has($results, Str::replaceLast('[]', '.1', $baseName))) {
  275. // If value is optional, toss a coin on whether to set or not
  276. if ($isRequired || array_rand([true, false], 1)) {
  277. Arr::set($results, Str::replaceLast('.0', '.1', $dotPath), $value);
  278. }
  279. }
  280. }
  281. }
  282. }
  283. public function addAuthField(array $parsedRoute): array
  284. {
  285. $parsedRoute['auth'] = null;
  286. $isApiAuthed = $this->config->get('auth.enabled', false);
  287. if (!$isApiAuthed || !$parsedRoute['metadata']['authenticated']) {
  288. return $parsedRoute;
  289. }
  290. $strategy = $this->config->get('auth.in');
  291. $parameterName = $this->config->get('auth.name');
  292. $faker = Factory::create();
  293. if ($this->config->get('faker_seed')) {
  294. $faker->seed($this->config->get('faker_seed'));
  295. }
  296. $token = $faker->shuffle('abcdefghkvaZVDPE1864563');
  297. $valueToUse = $this->config->get('auth.use_value');
  298. $valueToDisplay = $this->config->get('auth.placeholder');
  299. switch ($strategy) {
  300. case 'query':
  301. case 'query_or_body':
  302. $parsedRoute['auth'] = "cleanQueryParameters.$parameterName." . ($valueToUse ?: $token);
  303. $parsedRoute['queryParameters'][$parameterName] = [
  304. 'name' => $parameterName,
  305. 'type' => 'string',
  306. 'value' => $valueToDisplay ?: $token,
  307. 'description' => 'Authentication key.',
  308. 'required' => true,
  309. ];
  310. break;
  311. case 'body':
  312. $parsedRoute['auth'] = "cleanBodyParameters.$parameterName." . ($valueToUse ?: $token);
  313. $parsedRoute['bodyParameters'][$parameterName] = [
  314. 'name' => $parameterName,
  315. 'type' => 'string',
  316. 'value' => $valueToDisplay ?: $token,
  317. 'description' => 'Authentication key.',
  318. 'required' => true,
  319. ];
  320. break;
  321. case 'bearer':
  322. $parsedRoute['auth'] = "headers.Authorization.Bearer " . ($valueToUse ?: $token);
  323. $parsedRoute['headers']['Authorization'] = "Bearer " . ($valueToDisplay ?: $token);
  324. break;
  325. case 'basic':
  326. $parsedRoute['auth'] = "headers.Authorization.Basic " . ($valueToUse ?: base64_encode($token));
  327. $parsedRoute['headers']['Authorization'] = "Basic " . ($valueToDisplay ?: base64_encode($token));
  328. break;
  329. case 'header':
  330. $parsedRoute['auth'] = "headers.$parameterName." . ($valueToUse ?: $token);
  331. $parsedRoute['headers'][$parameterName] = $valueToDisplay ?: $token;
  332. break;
  333. }
  334. return $parsedRoute;
  335. }
  336. protected static function convertStringValueToUploadedFileInstance(string $filePath): UploadedFile
  337. {
  338. $fileName = basename($filePath);
  339. return new UploadedFile(
  340. $filePath, $fileName, mime_content_type($filePath), 0, false
  341. );
  342. }
  343. /**
  344. * Transform body parameters such that object fields have a `fields` property containing a list of all subfields
  345. * Subfields will be removed from the main parameter map
  346. * For instance, if $parameters is ['dad' => [], 'dad.cars' => [], 'dad.age' => []],
  347. * normalise this into ['dad' => [..., 'fields' => ['dad.cars' => [], 'dad.age' => []]]
  348. */
  349. public static function nestArrayAndObjectFields(array $parameters)
  350. {
  351. $finalParameters = [];
  352. foreach ($parameters as $name => $parameter) {
  353. if (Str::contains($name, '.')) { // Likely an object field
  354. // Get the various pieces of the name
  355. $parts = array_reverse(explode('.', $name));
  356. $fieldName = array_shift($parts);
  357. $baseName = join('.fields.', array_reverse($parts));
  358. // The type should be indicated in the source object by now; we don't need it in the name
  359. $normalisedBaseName = str_replace('[]', '.fields', $baseName);
  360. $dotPath = preg_replace('/\.fields$/', '', $normalisedBaseName) . '.fields.' . $fieldName;
  361. Arr::set($finalParameters, $dotPath, $parameter);
  362. } else { // A regular field
  363. $parameter['fields'] = [];
  364. $finalParameters[$name] = $parameter;
  365. }
  366. }
  367. return $finalParameters;
  368. }
  369. }