Generator.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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\Utils as u;
  11. use ReflectionClass;
  12. use ReflectionFunctionAbstract;
  13. class Generator
  14. {
  15. /**
  16. * @var DocumentationConfig
  17. */
  18. private $config;
  19. public function __construct(DocumentationConfig $config = null)
  20. {
  21. // If no config is injected, pull from global
  22. $this->config = $config ?: new DocumentationConfig(config('scribe'));
  23. }
  24. /**
  25. * @param Route $route
  26. *
  27. * @return mixed
  28. */
  29. public function getUri(Route $route)
  30. {
  31. return $route->uri();
  32. }
  33. /**
  34. * @param Route $route
  35. *
  36. * @return mixed
  37. */
  38. public function getMethods(Route $route)
  39. {
  40. $methods = $route->methods();
  41. // Laravel adds an automatic "HEAD" endpoint for each GET request, so we'll strip that out,
  42. // but not if there's only one method (means it was intentional)
  43. if (count($methods) === 1) {
  44. return $methods;
  45. }
  46. return array_diff($methods, ['HEAD']);
  47. }
  48. /**
  49. * @param \Illuminate\Routing\Route $route
  50. * @param array $routeRules Rules to apply when generating documentation for this route
  51. *
  52. * @throws \ReflectionException
  53. *
  54. * @return array
  55. */
  56. public function processRoute(Route $route, array $routeRules = [])
  57. {
  58. [$controllerName, $methodName] = u::getRouteClassAndMethodNames($route);
  59. $controller = new ReflectionClass($controllerName);
  60. $method = u::getReflectedRouteMethod([$controllerName, $methodName]);
  61. $parsedRoute = [
  62. 'id' => md5($this->getUri($route) . ':' . implode($this->getMethods($route))),
  63. 'methods' => $this->getMethods($route),
  64. 'uri' => $this->getUri($route),
  65. ];
  66. $metadata = $this->fetchMetadata($controller, $method, $route, $routeRules, $parsedRoute);
  67. $parsedRoute['metadata'] = $metadata;
  68. $urlParameters = $this->fetchUrlParameters($controller, $method, $route, $routeRules, $parsedRoute);
  69. $parsedRoute['urlParameters'] = $urlParameters;
  70. $parsedRoute['cleanUrlParameters'] = self::cleanParams($urlParameters);
  71. $parsedRoute['boundUri'] = u::getFullUrl($route, $parsedRoute['cleanUrlParameters']);
  72. $parsedRoute = $this->addAuthField($parsedRoute);
  73. $queryParameters = $this->fetchQueryParameters($controller, $method, $route, $routeRules, $parsedRoute);
  74. $parsedRoute['queryParameters'] = $queryParameters;
  75. $parsedRoute['cleanQueryParameters'] = self::cleanParams($queryParameters);
  76. $headers = $this->fetchRequestHeaders($controller, $method, $route, $routeRules, $parsedRoute);
  77. $parsedRoute['headers'] = $headers;
  78. $bodyParameters = $this->fetchBodyParameters($controller, $method, $route, $routeRules, $parsedRoute);
  79. $parsedRoute['bodyParameters'] = $bodyParameters;
  80. $parsedRoute['cleanBodyParameters'] = self::cleanParams($bodyParameters);
  81. if (count($parsedRoute['cleanBodyParameters']) && !isset($parsedRoute['headers']['Content-Type'])) {
  82. // Set content type if the user forgot to set it
  83. $parsedRoute['headers']['Content-Type'] = 'application/json';
  84. }
  85. [$files, $regularParameters] = collect($parsedRoute['cleanBodyParameters'])->partition(function ($example) {
  86. return $example instanceof UploadedFile;
  87. });
  88. if (count($files)) {
  89. $parsedRoute['headers']['Content-Type'] = 'multipart/form-data';
  90. }
  91. $parsedRoute['fileParameters'] = $files->toArray();
  92. $parsedRoute['cleanBodyParameters'] = $regularParameters->toArray();
  93. $responses = $this->fetchResponses($controller, $method, $route, $routeRules, $parsedRoute);
  94. $parsedRoute['responses'] = $responses;
  95. $parsedRoute['showresponse'] = ! empty($responses);
  96. $responseFields = $this->fetchResponseFields($controller, $method, $route, $routeRules, $parsedRoute);
  97. $parsedRoute['responseFields'] = $responseFields;
  98. return $parsedRoute;
  99. }
  100. protected function fetchMetadata(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  101. {
  102. $context['metadata'] = [
  103. 'groupName' => $this->config->get('default_group', ''),
  104. 'groupDescription' => '',
  105. 'title' => '',
  106. 'description' => '',
  107. 'authenticated' => false,
  108. ];
  109. return $this->iterateThroughStrategies('metadata', $context, [$route, $controller, $method, $rulesToApply]);
  110. }
  111. protected function fetchUrlParameters(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  112. {
  113. return $this->iterateThroughStrategies('urlParameters', $context, [$route, $controller, $method, $rulesToApply]);
  114. }
  115. protected function fetchQueryParameters(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  116. {
  117. return $this->iterateThroughStrategies('queryParameters', $context, [$route, $controller, $method, $rulesToApply]);
  118. }
  119. protected function fetchBodyParameters(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  120. {
  121. return $this->iterateThroughStrategies('bodyParameters', $context, [$route, $controller, $method, $rulesToApply]);
  122. }
  123. protected function fetchResponses(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  124. {
  125. $responses = $this->iterateThroughStrategies('responses', $context, [$route, $controller, $method, $rulesToApply]);
  126. if (count($responses)) {
  127. return array_filter($responses, function ($response) {
  128. return $response['content'] != null;
  129. });
  130. }
  131. return [];
  132. }
  133. protected function fetchResponseFields(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  134. {
  135. return $this->iterateThroughStrategies('responseFields', $context, [$route, $controller, $method, $rulesToApply]);
  136. }
  137. protected function fetchRequestHeaders(ReflectionClass $controller, ReflectionFunctionAbstract $method, Route $route, array $rulesToApply, array $context = [])
  138. {
  139. $headers = $this->iterateThroughStrategies('headers', $context, [$route, $controller, $method, $rulesToApply]);
  140. return array_filter($headers);
  141. }
  142. protected function iterateThroughStrategies(string $stage, array $extractedData, array $arguments)
  143. {
  144. $defaultStrategies = [
  145. 'metadata' => [
  146. \Knuckles\Scribe\Extracting\Strategies\Metadata\GetFromDocBlocks::class,
  147. ],
  148. 'urlParameters' => [
  149. \Knuckles\Scribe\Extracting\Strategies\UrlParameters\GetFromUrlParamTag::class,
  150. ],
  151. 'queryParameters' => [
  152. \Knuckles\Scribe\Extracting\Strategies\QueryParameters\GetFromQueryParamTag::class,
  153. ],
  154. 'headers' => [
  155. \Knuckles\Scribe\Extracting\Strategies\Headers\GetFromRouteRules::class,
  156. \Knuckles\Scribe\Extracting\Strategies\Headers\GetFromHeaderTag::class,
  157. ],
  158. 'bodyParameters' => [
  159. \Knuckles\Scribe\Extracting\Strategies\BodyParameters\GetFromFormRequest::class,
  160. \Knuckles\Scribe\Extracting\Strategies\BodyParameters\GetFromBodyParamTag::class,
  161. ],
  162. 'responses' => [
  163. \Knuckles\Scribe\Extracting\Strategies\Responses\UseTransformerTags::class,
  164. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseTag::class,
  165. \Knuckles\Scribe\Extracting\Strategies\Responses\UseResponseFileTag::class,
  166. \Knuckles\Scribe\Extracting\Strategies\Responses\UseApiResourceTags::class,
  167. \Knuckles\Scribe\Extracting\Strategies\Responses\ResponseCalls::class,
  168. ],
  169. 'responseFields' => [
  170. \Knuckles\Scribe\Extracting\Strategies\ResponseFields\GetFromResponseFieldTag::class,
  171. ],
  172. ];
  173. // Use the default strategies for the stage, unless they were explicitly set
  174. $strategies = $this->config->get("strategies.$stage", $defaultStrategies[$stage]);
  175. $extractedData[$stage] = $extractedData[$stage] ?? [];
  176. foreach ($strategies as $strategyClass) {
  177. /** @var Strategy $strategy */
  178. $strategy = new $strategyClass($this->config);
  179. $strategyArgs = $arguments;
  180. $strategyArgs[] = $extractedData;
  181. $results = $strategy(...$strategyArgs);
  182. if (! is_null($results)) {
  183. foreach ($results as $index => $item) {
  184. if ($stage == 'responses') {
  185. // Responses from different strategies are all added, not overwritten
  186. $extractedData[$stage][] = $item;
  187. continue;
  188. }
  189. // We're using a for loop rather than array_merge or +=
  190. // so it does not renumber numeric keys and also allows values to be overwritten
  191. // Don't allow overwriting if an empty value is trying to replace a set one
  192. if (! in_array($extractedData[$stage], [null, ''], true) && in_array($item, [null, ''], true)) {
  193. continue;
  194. } else {
  195. $extractedData[$stage][$index] = $item;
  196. }
  197. }
  198. }
  199. }
  200. return $extractedData[$stage];
  201. }
  202. /**
  203. * This method prepares and simplifies request parameters for use in example requests and response calls.
  204. * It takes in an array with rich details about a parameter eg
  205. * ['age' => [
  206. * 'description' => 'The age',
  207. * 'value' => 12,
  208. * 'required' => false,
  209. * ]
  210. * And transforms them into key-value pairs : ['age' => 12]
  211. * It also filters out parameters which have null values and have 'required' as false.
  212. * It converts all file params that have string examples to actual files (instances of UploadedFile).
  213. * Finally, it adds a '.0' key for each array parameter (eg users.* ->users.0),
  214. * so that the array ends up containing a 1-item array.
  215. *
  216. * @param array $params
  217. *
  218. * @return array
  219. */
  220. public static function cleanParams(array $params): array
  221. {
  222. $cleanParams = [];
  223. // Remove params which have no examples and are optional.
  224. $params = array_filter($params, function ($details) {
  225. return ! (is_null($details['value']) && $details['required'] === false);
  226. });
  227. foreach ($params as $paramName => $details) {
  228. if (($details['type'] ?? '') === 'file' && is_string($details['value'])) {
  229. // Convert any string file examples to instances of UploadedFile
  230. $filePath = $details['value'];
  231. $fileName = basename($filePath);
  232. $details['value'] = new UploadedFile(
  233. $filePath, $fileName, mime_content_type($filePath), 0,false
  234. );
  235. }
  236. self::generateConcreteKeysForArrayParameters(
  237. $paramName,
  238. $details['value'],
  239. $cleanParams
  240. );
  241. }
  242. return $cleanParams;
  243. }
  244. /**
  245. * For each array notation parameter (eg user.*, item.*.name, object.*.*, user[])
  246. * add a key that represents a "concrete" number (eg user.0, item.0.name, object.0.0, user.0 with the same value.
  247. * That way, we always have an array of length 1 for each array key
  248. *
  249. * @param string $paramName
  250. * @param mixed $paramExample
  251. * @param array $cleanParams The array that holds the result
  252. *
  253. * @return void
  254. */
  255. protected static function generateConcreteKeysForArrayParameters($paramName, $paramExample, array &$cleanParams = [])
  256. {
  257. if (Str::contains($paramName, '[')) {
  258. // Replace usages of [] with dot notation
  259. $paramName = str_replace(['][', '[', ']', '..'], ['.', '.', '', '.*.'], $paramName);
  260. }
  261. // Then generate a sample item for the dot notation
  262. Arr::set($cleanParams, str_replace(['.*', '*.'], ['.0','0.'], $paramName), $paramExample);
  263. }
  264. public function addAuthField(array $parsedRoute): array
  265. {
  266. $parsedRoute['auth'] = null;
  267. $isApiAuthed = $this->config->get('auth.enabled', false);
  268. if (!$isApiAuthed || !$parsedRoute['metadata']['authenticated']) {
  269. return $parsedRoute;
  270. }
  271. $strategy = $this->config->get('auth.in');
  272. $parameterName = $this->config->get('auth.name');
  273. $faker = Factory::create();
  274. if ($this->config->get('faker_seed')) {
  275. $faker->seed($this->config->get('faker_seed'));
  276. }
  277. $token = $faker->shuffle('abcdefghkvaZVDPE1864563');
  278. $valueToUse = $this->config->get('auth.use_value');
  279. $valueToDisplay = $this->config->get('auth.placeholder');
  280. switch ($strategy) {
  281. case 'query':
  282. case 'query_or_body':
  283. $parsedRoute['auth'] = "cleanQueryParameters.$parameterName.".($valueToUse ?: $token);
  284. $parsedRoute['queryParameters'][$parameterName] = [
  285. 'name' => $parameterName,
  286. 'value' => $valueToDisplay ?:$token,
  287. 'description' => '',
  288. 'required' => true,
  289. ];
  290. break;
  291. case 'body':
  292. $parsedRoute['auth'] = "cleanBodyParameters.$parameterName.".($valueToUse ?: $token);
  293. $parsedRoute['bodyParameters'][$parameterName] = [
  294. 'name' => $parameterName,
  295. 'type' => 'string',
  296. 'value' => $valueToDisplay ?: $token,
  297. 'description' => '',
  298. 'required' => true,
  299. ];
  300. break;
  301. case 'bearer':
  302. $parsedRoute['auth'] = "headers.Authorization.Bearer ".($valueToUse ?: $token);
  303. $parsedRoute['headers']['Authorization'] = "Bearer ".($valueToDisplay ?: $token);
  304. break;
  305. case 'basic':
  306. $parsedRoute['auth'] = "headers.Authorization.Basic ".($valueToUse ?: base64_encode($token));
  307. $parsedRoute['headers']['Authorization'] = "Basic ".($valueToDisplay ?: base64_encode($token));
  308. break;
  309. case 'header':
  310. $parsedRoute['auth'] = "headers.$parameterName.".($valueToUse ?: $token);
  311. $parsedRoute['headers'][$parameterName] = $valueToDisplay ?: $token;
  312. break;
  313. }
  314. return $parsedRoute;
  315. }
  316. }