Generator.php 15 KB

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