Generator.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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::getFullUrl($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\GetFromUrlParamTag::class,
  165. ],
  166. 'queryParameters' => [
  167. \Knuckles\Scribe\Extracting\Strategies\QueryParameters\GetFromQueryParamTag::class,
  168. ],
  169. 'headers' => [
  170. \Knuckles\Scribe\Extracting\Strategies\Headers\GetFromRouteRules::class,
  171. \Knuckles\Scribe\Extracting\Strategies\Headers\GetFromHeaderTag::class,
  172. ],
  173. 'bodyParameters' => [
  174. \Knuckles\Scribe\Extracting\Strategies\BodyParameters\GetFromFormRequest::class,
  175. \Knuckles\Scribe\Extracting\Strategies\BodyParameters\GetFromBodyParamTag::class,
  176. ],
  177. 'responses' => [
  178. \Knuckles\Scribe\Extracting\Strategies\Responses\UseTransformerTags::class,
  179. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseTag::class,
  180. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseFileTag::class,
  181. \Knuckles\Scribe\Extracting\Strategies\Responses\UseApiResourceTags::class,
  182. \Knuckles\Scribe\Extracting\Strategies\Responses\ResponseCalls::class,
  183. ],
  184. 'responseFields' => [
  185. \Knuckles\Scribe\Extracting\Strategies\ResponseFields\GetFromResponseFieldTag::class,
  186. ],
  187. ];
  188. // Use the default strategies for the stage, unless they were explicitly set
  189. $strategies = $this->config->get("strategies.$stage", $defaultStrategies[$stage]);
  190. $extractedData[$stage] = $extractedData[$stage] ?? [];
  191. foreach ($strategies as $strategyClass) {
  192. /** @var Strategy $strategy */
  193. $strategy = new $strategyClass($this->config);
  194. $strategyArgs = $arguments;
  195. $strategyArgs[] = $extractedData;
  196. $results = $strategy(...$strategyArgs);
  197. if (!is_null($results)) {
  198. foreach ($results as $index => $item) {
  199. if ($stage == 'responses') {
  200. // Responses from different strategies are all added, not overwritten
  201. $extractedData[$stage][] = $item;
  202. continue;
  203. }
  204. // We're using a for loop rather than array_merge or +=
  205. // so it does not renumber numeric keys and also allows values to be overwritten
  206. // Don't allow overwriting if an empty value is trying to replace a set one
  207. if (!in_array($extractedData[$stage], [null, ''], true) && in_array($item, [null, ''], true)) {
  208. continue;
  209. } else {
  210. $extractedData[$stage][$index] = $item;
  211. }
  212. }
  213. }
  214. }
  215. return $extractedData[$stage];
  216. }
  217. /**
  218. * This method prepares and simplifies request parameters for use in example requests and response calls.
  219. * It takes in an array with rich details about a parameter eg
  220. * ['age' => [
  221. * 'description' => 'The age',
  222. * 'value' => 12,
  223. * 'required' => false,
  224. * ]]
  225. * And transforms them into key-example pairs : ['age' => 12]
  226. * It also filters out parameters which have null values and have 'required' as false.
  227. * It converts all file params that have string examples to actual files (instances of UploadedFile).
  228. *
  229. * @param array $parameters
  230. *
  231. * @return array
  232. */
  233. public static function cleanParams(array $parameters): array
  234. {
  235. $cleanParameters = [];
  236. foreach ($parameters as $paramName => $details) {
  237. // Remove params which have no examples and are optional.
  238. if (is_null($details['value']) && $details['required'] === false) {
  239. continue;
  240. }
  241. if (($details['type'] ?? '') === 'file' && is_string($details['value'])) {
  242. $details['value'] = self::convertStringValueToUploadedFileInstance($details['value']);
  243. }
  244. if (Str::contains($paramName, '.')) { // Object field
  245. self::setObject($cleanParameters, $paramName, $details['value'], $parameters);
  246. } else {
  247. $cleanParameters[$paramName] = $details['value'];
  248. }
  249. }
  250. return $cleanParameters;
  251. }
  252. public static function setObject(array &$results, string $path, $value, array $source)
  253. {
  254. if (Str::contains($path, '.')) {
  255. $parts = array_reverse(explode('.', $path));
  256. array_shift($parts); // Get rid of the field name
  257. $baseName = join('.', array_reverse($parts));
  258. // The type should be indicated in the source object by now; we don't need it in the name
  259. $normalisedBaseName = str_replace('[]', '', $baseName);
  260. $parentData = Arr::get($source, $normalisedBaseName);
  261. if ($parentData) {
  262. // Path we use for lodash set
  263. $dotPath = str_replace('[]', '.0', $path);
  264. $noValue = new \stdClass();
  265. if ($parentData['type'] === 'object') {
  266. if (Arr::get($results, $dotPath, $noValue) === $noValue) {
  267. Arr::set($results, $dotPath, $value);
  268. }
  269. } else if ($parentData['type'] === 'object[]') {
  270. if (Arr::get($results, $dotPath, $noValue) === $noValue) {
  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::get($results, str_replace('[]', '.1', $baseName), $noValue) !== $noValue) {
  275. Arr::set($results, str_replace('.0', '.1', $dotPath), $value);
  276. }
  277. }
  278. }
  279. }
  280. }
  281. public function addAuthField(array $parsedRoute): array
  282. {
  283. $parsedRoute['auth'] = null;
  284. $isApiAuthed = $this->config->get('auth.enabled', false);
  285. if (!$isApiAuthed || !$parsedRoute['metadata']['authenticated']) {
  286. return $parsedRoute;
  287. }
  288. $strategy = $this->config->get('auth.in');
  289. $parameterName = $this->config->get('auth.name');
  290. $faker = Factory::create();
  291. if ($this->config->get('faker_seed')) {
  292. $faker->seed($this->config->get('faker_seed'));
  293. }
  294. $token = $faker->shuffle('abcdefghkvaZVDPE1864563');
  295. $valueToUse = $this->config->get('auth.use_value');
  296. $valueToDisplay = $this->config->get('auth.placeholder');
  297. switch ($strategy) {
  298. case 'query':
  299. case 'query_or_body':
  300. $parsedRoute['auth'] = "cleanQueryParameters.$parameterName." . ($valueToUse ?: $token);
  301. $parsedRoute['queryParameters'][$parameterName] = [
  302. 'name' => $parameterName,
  303. 'value' => $valueToDisplay ?: $token,
  304. 'description' => '',
  305. 'required' => true,
  306. ];
  307. break;
  308. case 'body':
  309. $parsedRoute['auth'] = "cleanBodyParameters.$parameterName." . ($valueToUse ?: $token);
  310. $parsedRoute['bodyParameters'][$parameterName] = [
  311. 'name' => $parameterName,
  312. 'type' => 'string',
  313. 'value' => $valueToDisplay ?: $token,
  314. 'description' => '',
  315. 'required' => true,
  316. ];
  317. break;
  318. case 'bearer':
  319. $parsedRoute['auth'] = "headers.Authorization.Bearer " . ($valueToUse ?: $token);
  320. $parsedRoute['headers']['Authorization'] = "Bearer " . ($valueToDisplay ?: $token);
  321. break;
  322. case 'basic':
  323. $parsedRoute['auth'] = "headers.Authorization.Basic " . ($valueToUse ?: base64_encode($token));
  324. $parsedRoute['headers']['Authorization'] = "Basic " . ($valueToDisplay ?: base64_encode($token));
  325. break;
  326. case 'header':
  327. $parsedRoute['auth'] = "headers.$parameterName." . ($valueToUse ?: $token);
  328. $parsedRoute['headers'][$parameterName] = $valueToDisplay ?: $token;
  329. break;
  330. }
  331. return $parsedRoute;
  332. }
  333. protected static function convertStringValueToUploadedFileInstance(string $filePath): UploadedFile
  334. {
  335. $fileName = basename($filePath);
  336. return new UploadedFile(
  337. $filePath, $fileName, mime_content_type($filePath), 0, false
  338. );
  339. }
  340. /**
  341. * Transform body parameters such that object fields have a `fields` property containing a list of all subfields
  342. * Subfields will be removed from the main parameter map
  343. * For instance, if $parameters is ['dad' => [], 'dad.cars' => [], 'dad.age' => []],
  344. * normalise this into ['dad' => [..., 'fields' => ['dad.cars' => [], 'dad.age' => []]]
  345. */
  346. public static function nestArrayAndObjectFields(array $parameters)
  347. {
  348. $finalParameters = [];
  349. foreach ($parameters as $name => $parameter) {
  350. if (Str::contains($name, '.')) { // Likely an object field
  351. // Get the various pieces of the name
  352. $parts = array_reverse(explode('.', $name));
  353. $fieldName = array_shift($parts);
  354. $baseName = join('.fields.', array_reverse($parts));
  355. // The type should be indicated in the source object by now; we don't need it in the name
  356. $normalisedBaseName = str_replace('[]', '.fields', $baseName);
  357. $dotPath = preg_replace('/\.fields$/', '', $normalisedBaseName) . '.fields.' . $fieldName;
  358. Arr::set($finalParameters, $dotPath, $parameter);
  359. } else { // A regular field
  360. $parameter['fields'] = [];
  361. $finalParameters[$name] = $parameter;
  362. }
  363. }
  364. return $finalParameters;
  365. }
  366. }