Extractor.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. namespace Knuckles\Scribe\Extracting;
  3. use Knuckles\Camel\Extraction\ExtractedEndpointData;
  4. use Knuckles\Camel\Extraction\Metadata;
  5. use Knuckles\Camel\Extraction\Parameter;
  6. use Faker\Factory;
  7. use Illuminate\Http\Testing\File;
  8. use Illuminate\Http\UploadedFile;
  9. use Illuminate\Routing\Route;
  10. use Illuminate\Support\Arr;
  11. use Illuminate\Support\Str;
  12. use Knuckles\Camel\Extraction\ResponseCollection;
  13. use Knuckles\Camel\Extraction\ResponseField;
  14. use Knuckles\Camel\Output\OutputEndpointData;
  15. use Knuckles\Scribe\Tools\DocumentationConfig;
  16. use Knuckles\Scribe\Tools\RoutePatternMatcher;
  17. class Extractor
  18. {
  19. private DocumentationConfig $config;
  20. use ParamHelpers;
  21. private static ?Route $routeBeingProcessed = null;
  22. public function __construct(DocumentationConfig $config = null)
  23. {
  24. // If no config is injected, pull from global
  25. $this->config = $config ?: new DocumentationConfig(config('scribe'));
  26. }
  27. /**
  28. * External interface that allows users to know what route is currently being processed
  29. */
  30. public static function getRouteBeingProcessed(): ?Route
  31. {
  32. return self::$routeBeingProcessed;
  33. }
  34. /**
  35. * @param Route $route
  36. * @param array $routeRules Rules to apply when generating documentation for this route
  37. *
  38. * @return ExtractedEndpointData
  39. *
  40. */
  41. public function processRoute(Route $route, array $routeRules = []): ExtractedEndpointData
  42. {
  43. self::$routeBeingProcessed = $route;
  44. $endpointData = ExtractedEndpointData::fromRoute($route);
  45. $inheritedDocsOverrides = [];
  46. if ($endpointData->controller->hasMethod('inheritedDocsOverrides')) {
  47. $inheritedDocsOverrides = call_user_func([$endpointData->controller->getName(), 'inheritedDocsOverrides']);
  48. $inheritedDocsOverrides = $inheritedDocsOverrides[$endpointData->method->getName()] ?? [];
  49. }
  50. $this->fetchMetadata($endpointData, $routeRules);
  51. $this->mergeInheritedMethodsData('metadata', $endpointData, $inheritedDocsOverrides);
  52. $this->fetchUrlParameters($endpointData, $routeRules);
  53. $this->mergeInheritedMethodsData('urlParameters', $endpointData, $inheritedDocsOverrides);
  54. $endpointData->cleanUrlParameters = self::cleanParams($endpointData->urlParameters);
  55. $this->addAuthField($endpointData);
  56. $this->fetchQueryParameters($endpointData, $routeRules);
  57. $this->mergeInheritedMethodsData('queryParameters', $endpointData, $inheritedDocsOverrides);
  58. $endpointData->cleanQueryParameters = self::cleanParams($endpointData->queryParameters);
  59. $this->fetchRequestHeaders($endpointData, $routeRules);
  60. $this->mergeInheritedMethodsData('headers', $endpointData, $inheritedDocsOverrides);
  61. $this->fetchBodyParameters($endpointData, $routeRules);
  62. $endpointData->cleanBodyParameters = self::cleanParams($endpointData->bodyParameters);
  63. $this->mergeInheritedMethodsData('bodyParameters', $endpointData, $inheritedDocsOverrides);
  64. if (count($endpointData->cleanBodyParameters) && !isset($endpointData->headers['Content-Type'])) {
  65. // Set content type if the user forgot to set it
  66. $endpointData->headers['Content-Type'] = 'application/json';
  67. }
  68. // We need to do all this so response calls can work correctly,
  69. // even though they're only needed for output
  70. // Note that this
  71. [$files, $regularParameters] = OutputEndpointData::splitIntoFileAndRegularParameters($endpointData->cleanBodyParameters);
  72. if (count($files)) {
  73. $endpointData->headers['Content-Type'] = 'multipart/form-data';
  74. }
  75. $endpointData->fileParameters = $files;
  76. $endpointData->cleanBodyParameters = $regularParameters;
  77. $this->fetchResponses($endpointData, $routeRules);
  78. $this->mergeInheritedMethodsData('responses', $endpointData, $inheritedDocsOverrides);
  79. $this->fetchResponseFields($endpointData, $routeRules);
  80. $this->mergeInheritedMethodsData('responseFields', $endpointData, $inheritedDocsOverrides);
  81. self::$routeBeingProcessed = null;
  82. return $endpointData;
  83. }
  84. protected function fetchMetadata(ExtractedEndpointData $endpointData, array $rulesToApply): void
  85. {
  86. $endpointData->metadata = new Metadata([
  87. 'groupName' => $this->config->get('groups.default', ''),
  88. "authenticated" => $this->config->get("auth.default", false),
  89. ]);
  90. $this->iterateThroughStrategies('metadata', $endpointData, $rulesToApply, function ($results) use ($endpointData) {
  91. foreach ($results as $key => $item) {
  92. $hadPreviousValue = !is_null($endpointData->metadata->$key);
  93. $noNewValueSet = is_null($item) || $item === "";
  94. if ($hadPreviousValue && $noNewValueSet) {
  95. continue;
  96. }
  97. $endpointData->metadata->$key = $item;
  98. }
  99. });
  100. }
  101. protected function fetchUrlParameters(ExtractedEndpointData $endpointData, array $rulesToApply): void
  102. {
  103. $this->iterateThroughStrategies('urlParameters', $endpointData, $rulesToApply, function ($results) use ($endpointData) {
  104. foreach ($results as $key => $item) {
  105. if (empty($item['name'])) {
  106. $item['name'] = $key;
  107. }
  108. $endpointData->urlParameters[$key] = Parameter::create($item, $endpointData->urlParameters[$key] ?? []);
  109. }
  110. });
  111. }
  112. protected function fetchQueryParameters(ExtractedEndpointData $endpointData, array $rulesToApply): void
  113. {
  114. $this->iterateThroughStrategies('queryParameters', $endpointData, $rulesToApply, function ($results) use ($endpointData) {
  115. foreach ($results as $key => $item) {
  116. if (empty($item['name'])) {
  117. $item['name'] = $key;
  118. }
  119. $endpointData->queryParameters[$key] = Parameter::create($item, $endpointData->queryParameters[$key] ?? []);
  120. }
  121. });
  122. }
  123. protected function fetchBodyParameters(ExtractedEndpointData $endpointData, array $rulesToApply): void
  124. {
  125. $this->iterateThroughStrategies('bodyParameters', $endpointData, $rulesToApply, function ($results) use ($endpointData) {
  126. foreach ($results as $key => $item) {
  127. if (empty($item['name'])) {
  128. $item['name'] = $key;
  129. }
  130. $endpointData->bodyParameters[$key] = Parameter::create($item, $endpointData->bodyParameters[$key] ?? []);
  131. }
  132. });
  133. }
  134. protected function fetchResponses(ExtractedEndpointData $endpointData, array $rulesToApply): void
  135. {
  136. $this->iterateThroughStrategies('responses', $endpointData, $rulesToApply, function ($results) use ($endpointData) {
  137. // Responses from different strategies are all added, not overwritten
  138. $endpointData->responses->concat($results);
  139. });
  140. // Ensure 200 responses come first
  141. $endpointData->responses = new ResponseCollection($endpointData->responses->sortBy('status')->values());
  142. }
  143. protected function fetchResponseFields(ExtractedEndpointData $endpointData, array $rulesToApply): void
  144. {
  145. $this->iterateThroughStrategies('responseFields', $endpointData, $rulesToApply, function ($results) use ($endpointData) {
  146. foreach ($results as $key => $item) {
  147. $endpointData->responseFields[$key] = Parameter::create($item, $endpointData->responseFields[$key] ?? []);
  148. }
  149. });
  150. }
  151. protected function fetchRequestHeaders(ExtractedEndpointData $endpointData, array $rulesToApply): void
  152. {
  153. $this->iterateThroughStrategies('headers', $endpointData, $rulesToApply, function ($results) use ($endpointData) {
  154. foreach ($results as $key => $item) {
  155. if ($item) {
  156. $endpointData->headers[$key] = $item;
  157. }
  158. }
  159. });
  160. }
  161. /**
  162. * Iterate through all defined strategies for this stage.
  163. * A strategy may return an array of attributes
  164. * to be added to that stage data, or it may modify the stage data directly.
  165. *
  166. * @param string $stage
  167. * @param ExtractedEndpointData $endpointData
  168. * @param array $rulesToApply
  169. * @param callable $handler Function to run after each strategy returns its results (an array).
  170. *
  171. */
  172. protected function iterateThroughStrategies(
  173. string $stage, ExtractedEndpointData $endpointData, array $rulesToApply, callable $handler
  174. ): void
  175. {
  176. $strategies = $this->config->get("strategies.$stage", []);
  177. $overrides = [];
  178. foreach ($strategies as $strategyClassOrTuple) {
  179. if (is_array($strategyClassOrTuple)) {
  180. [$strategyClass, $settings] = $strategyClassOrTuple;
  181. if ($strategyClass == 'override') {
  182. $overrides = $settings;
  183. continue;
  184. }
  185. $settings = self::transformOldRouteRulesIntoNewSettings($stage, $rulesToApply, $strategyClass, $settings);
  186. } else {
  187. $strategyClass = $strategyClassOrTuple;
  188. $settings = self::transformOldRouteRulesIntoNewSettings($stage, $rulesToApply, $strategyClass);
  189. }
  190. $routesToSkip = $settings["except"] ?? [];
  191. $routesToInclude = $settings["only"] ?? [];
  192. if (!empty($routesToSkip)) {
  193. if (RoutePatternMatcher::matches($endpointData->route, $routesToSkip)) {
  194. continue;
  195. }
  196. } elseif (!empty($routesToInclude)) {
  197. if (!RoutePatternMatcher::matches($endpointData->route, $routesToInclude)) {
  198. continue;
  199. }
  200. }
  201. $strategy = new $strategyClass($this->config);
  202. $results = $strategy($endpointData, $settings);
  203. if (is_array($results)) {
  204. $handler($results);
  205. }
  206. }
  207. if (!empty($overrides)) {
  208. $handler($overrides);
  209. }
  210. }
  211. /**
  212. * This method prepares and simplifies request parameters for use in example requests and response calls.
  213. * It takes in an array with rich details about a parameter eg
  214. * ['age' => new Parameter([
  215. * 'description' => 'The age',
  216. * 'example' => 12,
  217. * 'required' => false,
  218. * ])]
  219. * And transforms them into key-example pairs : ['age' => 12]
  220. * It also filters out parameters which have null values and have 'required' as false.
  221. * It converts all file params that have string examples to actual files (instances of UploadedFile).
  222. *
  223. * @param array<string,Parameter> $parameters
  224. *
  225. * @return array
  226. */
  227. public static function cleanParams(array $parameters): array
  228. {
  229. $cleanParameters = [];
  230. /**
  231. * @var string $paramName
  232. * @var Parameter $details
  233. */
  234. foreach ($parameters as $paramName => $details) {
  235. // Remove params which have no intentional examples and are optional.
  236. if (!$details->exampleWasSpecified) {
  237. if (is_null($details->example) && $details->required === false) {
  238. continue;
  239. }
  240. }
  241. if ($details->type === 'file') {
  242. if (is_string($details->example)) {
  243. $details->example = self::convertStringValueToUploadedFileInstance($details->example);
  244. } else if (is_null($details->example)) {
  245. $details->example = (new self)->generateDummyValue($details->type);
  246. }
  247. }
  248. if (Str::startsWith($paramName, '[].')) { // Entire body is an array
  249. if (empty($parameters["[]"])) { // Make sure there's a parent
  250. $cleanParameters["[]"] = [[], []];
  251. $parameters["[]"] = new Parameter([
  252. "name" => "[]",
  253. "type" => "object[]",
  254. "description" => "",
  255. "required" => true,
  256. "example" => [$paramName => $details->example],
  257. ]);
  258. }
  259. }
  260. if (Str::contains($paramName, '.')) { // Object field (or array of objects)
  261. self::setObject($cleanParameters, $paramName, $details->example, $parameters, $details->required);
  262. } else {
  263. $cleanParameters[$paramName] = $details->example;
  264. }
  265. }
  266. // Finally, if the body is an array, flatten it.
  267. if (isset($cleanParameters['[]'])) {
  268. $cleanParameters = $cleanParameters['[]'];
  269. }
  270. return $cleanParameters;
  271. }
  272. public static function setObject(array &$results, string $path, $value, array $source, bool $isRequired)
  273. {
  274. $parts = explode('.', $path);
  275. array_pop($parts); // Get rid of the field name
  276. $baseName = join('.', $parts);
  277. // For array fields, the type should be indicated in the source object by now;
  278. // eg test.items[] would actually be described as name: test.items, type: object[]
  279. // So we get rid of that ending []
  280. // For other fields (eg test.items[].name), it remains as-is
  281. $baseNameInOriginalParams = $baseName;
  282. while (Str::endsWith($baseNameInOriginalParams, '[]')) {
  283. $baseNameInOriginalParams = substr($baseNameInOriginalParams, 0, -2);
  284. }
  285. // When the body is an array, param names will be "[].paramname",
  286. // so $baseNameInOriginalParams here will be empty
  287. if (Str::startsWith($path, '[].')) {
  288. $baseNameInOriginalParams = '[]';
  289. }
  290. if (Arr::has($source, $baseNameInOriginalParams)) {
  291. /** @var Parameter $parentData */
  292. $parentData = Arr::get($source, $baseNameInOriginalParams);
  293. // Path we use for data_set
  294. $dotPath = str_replace('[]', '.0', $path);
  295. // Don't overwrite parent if there's already data there
  296. if ($parentData->type === 'object') {
  297. $parentPath = explode('.', $dotPath);
  298. $property = array_pop($parentPath);
  299. $parentPath = implode('.', $parentPath);
  300. $exampleFromParent = Arr::get($results, $dotPath) ?? $parentData->example[$property] ?? null;
  301. if (empty($exampleFromParent)) {
  302. Arr::set($results, $dotPath, $value);
  303. }
  304. } else if ($parentData->type === 'object[]') {
  305. // When the body is an array, param names will be "[].paramname", so dot paths won't work correctly with "[]"
  306. if (Str::startsWith($path, '[].')) {
  307. $valueDotPath = substr($dotPath, 3); // Remove initial '.0.'
  308. if (isset($results['[]'][0]) && !Arr::has($results['[]'][0], $valueDotPath)) {
  309. Arr::set($results['[]'][0], $valueDotPath, $value);
  310. }
  311. } else {
  312. $parentPath = explode('.', $dotPath);
  313. $index = (int)array_pop($parentPath);
  314. $parentPath = implode('.', $parentPath);
  315. $exampleFromParent = Arr::get($results, $dotPath) ?? $parentData->example[$index] ?? null;
  316. if (empty($exampleFromParent)) {
  317. Arr::set($results, $dotPath, $value);
  318. }
  319. }
  320. }
  321. }
  322. }
  323. public function addAuthField(ExtractedEndpointData $endpointData): void
  324. {
  325. $isApiAuthed = $this->config->get('auth.enabled', false);
  326. if (!$isApiAuthed || !$endpointData->metadata->authenticated) {
  327. return;
  328. }
  329. $strategy = $this->config->get('auth.in');
  330. $parameterName = $this->config->get('auth.name');
  331. $faker = Factory::create();
  332. if ($seed = $this->config->get('examples.faker_seed')) {
  333. $faker->seed($seed);
  334. }
  335. $token = $faker->shuffleString('abcdefghkvaZVDPE1864563');
  336. $valueToUse = $this->config->get('auth.use_value');
  337. $valueToDisplay = $this->config->get('auth.placeholder');
  338. switch ($strategy) {
  339. case 'query':
  340. case 'query_or_body':
  341. $endpointData->auth = ["queryParameters", $parameterName, $valueToUse ?: $token];
  342. $endpointData->queryParameters[$parameterName] = new Parameter([
  343. 'name' => $parameterName,
  344. 'type' => 'string',
  345. 'example' => $valueToDisplay ?: $token,
  346. 'description' => 'Authentication key.',
  347. 'required' => true,
  348. ]);
  349. return;
  350. case 'body':
  351. $endpointData->auth = ["bodyParameters", $parameterName, $valueToUse ?: $token];
  352. $endpointData->bodyParameters[$parameterName] = new Parameter([
  353. 'name' => $parameterName,
  354. 'type' => 'string',
  355. 'example' => $valueToDisplay ?: $token,
  356. 'description' => 'Authentication key.',
  357. 'required' => true,
  358. ]);
  359. return;
  360. case 'bearer':
  361. $endpointData->auth = ["headers", "Authorization", "Bearer " . ($valueToUse ?: $token)];
  362. $endpointData->headers['Authorization'] = "Bearer " . ($valueToDisplay ?: $token);
  363. return;
  364. case 'basic':
  365. $endpointData->auth = ["headers", "Authorization", "Basic " . ($valueToUse ?: base64_encode($token))];
  366. $endpointData->headers['Authorization'] = "Basic " . ($valueToDisplay ?: base64_encode($token));
  367. return;
  368. case 'header':
  369. $endpointData->auth = ["headers", $parameterName, $valueToUse ?: $token];
  370. $endpointData->headers[$parameterName] = $valueToDisplay ?: $token;
  371. return;
  372. }
  373. }
  374. protected static function convertStringValueToUploadedFileInstance(string $filePath): UploadedFile
  375. {
  376. $fileName = basename($filePath);
  377. return new File($fileName, fopen($filePath, 'r'));
  378. }
  379. protected function mergeInheritedMethodsData(string $stage, ExtractedEndpointData $endpointData, array $inheritedDocsOverrides = []): void
  380. {
  381. $overrides = $inheritedDocsOverrides[$stage] ?? [];
  382. $normalizeParamData = fn($data, $key) => array_merge($data, ["name" => $key]);
  383. if (is_array($overrides)) {
  384. foreach ($overrides as $key => $item) {
  385. switch ($stage) {
  386. case "responses":
  387. $endpointData->responses->concat($overrides);
  388. $endpointData->responses->sortBy('status');
  389. break;
  390. case "urlParameters":
  391. case "bodyParameters":
  392. case "queryParameters":
  393. $endpointData->$stage[$key] = Parameter::make($normalizeParamData($item, $key));
  394. break;
  395. case "responseFields":
  396. $endpointData->$stage[$key] = ResponseField::make($normalizeParamData($item, $key));
  397. break;
  398. default:
  399. $endpointData->$stage[$key] = $item;
  400. }
  401. }
  402. } else if (is_callable($overrides)) {
  403. $results = $overrides($endpointData);
  404. $endpointData->$stage = match ($stage) {
  405. "responses" => ResponseCollection::make($results),
  406. "urlParameters", "bodyParameters", "queryParameters" => collect($results)->map(fn($param, $name) => Parameter::make($normalizeParamData($param, $name)))->all(),
  407. "responseFields" => collect($results)->map(fn($field, $name) => ResponseField::make($normalizeParamData($field, $name)))->all(),
  408. default => $results,
  409. };
  410. }
  411. }
  412. // In the past, we defined rules at the `routes` level;
  413. // currently, they should be defined as parameters to the ResponseCalls strategy
  414. public static function transformOldRouteRulesIntoNewSettings($stage, $rulesToApply, $strategyName, $strategySettings = [])
  415. {
  416. if ($stage == 'headers' && Str::is('*RouteRules*', $strategyName)) {
  417. return $rulesToApply;
  418. }
  419. if ($stage == 'responses' && Str::is('*ResponseCalls*', $strategyName) &&!empty($rulesToApply['response_calls'])) {
  420. // Transform `methods` to `only`
  421. $strategySettings = [];
  422. if (isset($rulesToApply['response_calls']['methods'])) {
  423. if(empty($rulesToApply['response_calls']['methods'])) {
  424. // This means all routes are forbidden
  425. $strategySettings['except'] = ["*"];
  426. } else {
  427. $strategySettings['only'] = array_map(
  428. fn($method) => "$method *",
  429. $rulesToApply['response_calls']['methods']
  430. );
  431. }
  432. }
  433. // Copy all other keys over as is
  434. foreach (array_keys($rulesToApply['response_calls']) as $key) {
  435. if ($key == 'methods') continue;
  436. $strategySettings[$key] = $rulesToApply['response_calls'][$key];
  437. }
  438. }
  439. return $strategySettings;
  440. }
  441. }