Generator.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <?php
  2. namespace Mpociot\ApiDoc\Tools;
  3. use Faker\Factory;
  4. use ReflectionClass;
  5. use ReflectionMethod;
  6. use Illuminate\Routing\Route;
  7. use Mpociot\Reflection\DocBlock;
  8. use Mpociot\Reflection\DocBlock\Tag;
  9. use Mpociot\ApiDoc\Tools\Traits\ParamHelpers;
  10. class Generator
  11. {
  12. use ParamHelpers;
  13. /**
  14. * @var DocumentationConfig
  15. */
  16. private $config;
  17. public function __construct(DocumentationConfig $config = null)
  18. {
  19. // If no config is injected, pull from global
  20. $this->config = $config ?: new DocumentationConfig(config('apidoc'));
  21. }
  22. /**
  23. * @param Route $route
  24. *
  25. * @return mixed
  26. */
  27. public function getUri(Route $route)
  28. {
  29. return $route->uri();
  30. }
  31. /**
  32. * @param Route $route
  33. *
  34. * @return mixed
  35. */
  36. public function getMethods(Route $route)
  37. {
  38. return array_diff($route->methods(), ['HEAD']);
  39. }
  40. /**
  41. * @param \Illuminate\Routing\Route $route
  42. * @param array $apply Rules to apply when generating documentation for this route
  43. *
  44. * @return array
  45. */
  46. public function processRoute(Route $route, array $rulesToApply = [])
  47. {
  48. list($class, $method) = Utils::getRouteActionUses($route->getAction());
  49. $controller = new ReflectionClass($class);
  50. $method = $controller->getMethod($method);
  51. $routeGroup = $this->getRouteGroup($controller, $method);
  52. $docBlock = $this->parseDocBlock($method);
  53. $bodyParameters = $this->getBodyParameters($method, $docBlock['tags']);
  54. $queryParameters = $this->getQueryParameters($method, $docBlock['tags']);
  55. $content = ResponseResolver::getResponse($route, $docBlock['tags'], [
  56. 'rules' => $rulesToApply,
  57. 'body' => $bodyParameters,
  58. 'query' => $queryParameters,
  59. ]);
  60. $parsedRoute = [
  61. 'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
  62. 'group' => $routeGroup,
  63. 'title' => $docBlock['short'],
  64. 'description' => $docBlock['long'],
  65. 'methods' => $this->getMethods($route),
  66. 'uri' => $this->getUri($route),
  67. 'boundUri' => Utils::getFullUrl($route, $rulesToApply['bindings'] ?? ($rulesToApply['response_calls']['bindings'] ?? [])),
  68. 'queryParameters' => $queryParameters,
  69. 'bodyParameters' => $bodyParameters,
  70. 'cleanBodyParameters' => $this->cleanParams($bodyParameters),
  71. 'cleanQueryParameters' => $this->cleanParams($queryParameters),
  72. 'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
  73. 'response' => $content,
  74. 'showresponse' => ! empty($content),
  75. ];
  76. $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
  77. return $parsedRoute;
  78. }
  79. protected function getBodyParameters(ReflectionMethod $method, array $tags)
  80. {
  81. foreach ($method->getParameters() as $param) {
  82. $paramType = $param->getType();
  83. if ($paramType === null) {
  84. continue;
  85. }
  86. $parameterClassName = version_compare(phpversion(), '7.1.0', '<')
  87. ? $paramType->__toString()
  88. : $paramType->getName();
  89. try {
  90. $parameterClass = new ReflectionClass($parameterClassName);
  91. } catch (\ReflectionException $e) {
  92. continue;
  93. }
  94. if (class_exists('\Illuminate\Foundation\Http\FormRequest') && $parameterClass->isSubclassOf(\Illuminate\Foundation\Http\FormRequest::class) || class_exists('\Dingo\Api\Http\FormRequest') && $parameterClass->isSubclassOf(\Dingo\Api\Http\FormRequest::class)) {
  95. $formRequestDocBlock = new DocBlock($parameterClass->getDocComment());
  96. $bodyParametersFromDocBlock = $this->getBodyParametersFromDocBlock($formRequestDocBlock->getTags());
  97. if (count($bodyParametersFromDocBlock)) {
  98. return $bodyParametersFromDocBlock;
  99. }
  100. }
  101. }
  102. return $this->getBodyParametersFromDocBlock($tags);
  103. }
  104. /**
  105. * @param array $tags
  106. *
  107. * @return array
  108. */
  109. protected function getBodyParametersFromDocBlock(array $tags)
  110. {
  111. $parameters = collect($tags)
  112. ->filter(function ($tag) {
  113. return $tag instanceof Tag && $tag->getName() === 'bodyParam';
  114. })
  115. ->mapWithKeys(function ($tag) {
  116. preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
  117. $content = preg_replace('/\s?No-example.?/', '', $content);
  118. if (empty($content)) {
  119. // this means only name and type were supplied
  120. list($name, $type) = preg_split('/\s+/', $tag->getContent());
  121. $required = false;
  122. $description = '';
  123. } else {
  124. list($_, $name, $type, $required, $description) = $content;
  125. $description = trim($description);
  126. if ($description == 'required' && empty(trim($required))) {
  127. $required = $description;
  128. $description = '';
  129. }
  130. $required = trim($required) == 'required' ? true : false;
  131. }
  132. $type = $this->normalizeParameterType($type);
  133. list($description, $example) = $this->parseDescription($description, $type);
  134. $value = is_null($example) && ! $this->shouldExcludeExample($tag) ? $this->generateDummyValue($type) : $example;
  135. return [$name => compact('type', 'description', 'required', 'value')];
  136. })->toArray();
  137. return $parameters;
  138. }
  139. /**
  140. * @param ReflectionMethod $method
  141. * @param array $tags
  142. *
  143. * @return array
  144. */
  145. protected function getQueryParameters(ReflectionMethod $method, array $tags)
  146. {
  147. foreach ($method->getParameters() as $param) {
  148. $paramType = $param->getType();
  149. if ($paramType === null) {
  150. continue;
  151. }
  152. $parameterClassName = version_compare(phpversion(), '7.1.0', '<')
  153. ? $paramType->__toString()
  154. : $paramType->getName();
  155. try {
  156. $parameterClass = new ReflectionClass($parameterClassName);
  157. } catch (\ReflectionException $e) {
  158. continue;
  159. }
  160. if (class_exists('\Illuminate\Foundation\Http\FormRequest') && $parameterClass->isSubclassOf(\Illuminate\Foundation\Http\FormRequest::class) || class_exists('\Dingo\Api\Http\FormRequest') && $parameterClass->isSubclassOf(\Dingo\Api\Http\FormRequest::class)) {
  161. $formRequestDocBlock = new DocBlock($parameterClass->getDocComment());
  162. $queryParametersFromDocBlock = $this->getQueryParametersFromDocBlock($formRequestDocBlock->getTags());
  163. if (count($queryParametersFromDocBlock)) {
  164. return $queryParametersFromDocBlock;
  165. }
  166. }
  167. }
  168. return $this->getQueryParametersFromDocBlock($tags);
  169. }
  170. /**
  171. * @param array $tags
  172. *
  173. * @return array
  174. */
  175. protected function getQueryParametersFromDocBlock(array $tags)
  176. {
  177. $parameters = collect($tags)
  178. ->filter(function ($tag) {
  179. return $tag instanceof Tag && $tag->getName() === 'queryParam';
  180. })
  181. ->mapWithKeys(function ($tag) {
  182. preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
  183. $content = preg_replace('/\s?No-example.?/', '', $content);
  184. if (empty($content)) {
  185. // this means only name was supplied
  186. list($name) = preg_split('/\s+/', $tag->getContent());
  187. $required = false;
  188. $description = '';
  189. } else {
  190. list($_, $name, $required, $description) = $content;
  191. $description = trim($description);
  192. if ($description == 'required' && empty(trim($required))) {
  193. $required = $description;
  194. $description = '';
  195. }
  196. $required = trim($required) == 'required' ? true : false;
  197. }
  198. list($description, $value) = $this->parseDescription($description, 'string');
  199. if (is_null($value) && ! $this->shouldExcludeExample($tag)) {
  200. $value = str_contains($description, ['number', 'count', 'page'])
  201. ? $this->generateDummyValue('integer')
  202. : $this->generateDummyValue('string');
  203. }
  204. return [$name => compact('description', 'required', 'value')];
  205. })->toArray();
  206. return $parameters;
  207. }
  208. /**
  209. * @param array $tags
  210. *
  211. * @return bool
  212. */
  213. protected function getAuthStatusFromDocBlock(array $tags)
  214. {
  215. $authTag = collect($tags)
  216. ->first(function ($tag) {
  217. return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
  218. });
  219. return (bool) $authTag;
  220. }
  221. /**
  222. * @param ReflectionMethod $method
  223. *
  224. * @return array
  225. */
  226. protected function parseDocBlock(ReflectionMethod $method)
  227. {
  228. $comment = $method->getDocComment();
  229. $phpdoc = new DocBlock($comment);
  230. return [
  231. 'short' => $phpdoc->getShortDescription(),
  232. 'long' => $phpdoc->getLongDescription()->getContents(),
  233. 'tags' => $phpdoc->getTags(),
  234. ];
  235. }
  236. /**
  237. * @param ReflectionClass $controller
  238. * @param ReflectionMethod $method
  239. *
  240. * @return string
  241. */
  242. protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
  243. {
  244. // @group tag on the method overrides that on the controller
  245. $docBlockComment = $method->getDocComment();
  246. if ($docBlockComment) {
  247. $phpdoc = new DocBlock($docBlockComment);
  248. foreach ($phpdoc->getTags() as $tag) {
  249. if ($tag->getName() === 'group') {
  250. return $tag->getContent();
  251. }
  252. }
  253. }
  254. $docBlockComment = $controller->getDocComment();
  255. if ($docBlockComment) {
  256. $phpdoc = new DocBlock($docBlockComment);
  257. foreach ($phpdoc->getTags() as $tag) {
  258. if ($tag->getName() === 'group') {
  259. return $tag->getContent();
  260. }
  261. }
  262. }
  263. return $this->config->get(('default_group'));
  264. }
  265. private function normalizeParameterType($type)
  266. {
  267. $typeMap = [
  268. 'int' => 'integer',
  269. 'bool' => 'boolean',
  270. 'double' => 'float',
  271. ];
  272. return $type ? ($typeMap[$type] ?? $type) : 'string';
  273. }
  274. private function generateDummyValue(string $type)
  275. {
  276. $faker = Factory::create();
  277. if ($this->config->get('faker_seed')) {
  278. $faker->seed($this->config->get('faker_seed'));
  279. }
  280. $fakeFactories = [
  281. 'integer' => function () use ($faker) {
  282. return $faker->numberBetween(1, 20);
  283. },
  284. 'number' => function () use ($faker) {
  285. return $faker->randomFloat();
  286. },
  287. 'float' => function () use ($faker) {
  288. return $faker->randomFloat();
  289. },
  290. 'boolean' => function () use ($faker) {
  291. return $faker->boolean();
  292. },
  293. 'string' => function () use ($faker) {
  294. return $faker->word;
  295. },
  296. 'array' => function () {
  297. return [];
  298. },
  299. 'object' => function () {
  300. return new \stdClass;
  301. },
  302. ];
  303. $fakeFactory = $fakeFactories[$type] ?? $fakeFactories['string'];
  304. return $fakeFactory();
  305. }
  306. /**
  307. * Allows users to specify an example for the parameter by writing 'Example: the-example',
  308. * to be used in example requests and response calls.
  309. *
  310. * @param string $description
  311. * @param string $type The type of the parameter. Used to cast the example provided, if any.
  312. *
  313. * @return array The description and included example.
  314. */
  315. private function parseDescription(string $description, string $type)
  316. {
  317. $example = null;
  318. if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
  319. $description = $content[1];
  320. // examples are parsed as strings by default, we need to cast them properly
  321. $example = $this->castToType($content[2], $type);
  322. }
  323. return [$description, $example];
  324. }
  325. /**
  326. * Allows users to specify that we shouldn't generate an example for the parameter
  327. * by writing 'No-example'.
  328. *
  329. * @param Tag $tag
  330. *
  331. * @return bool Whether no example should be generated
  332. */
  333. private function shouldExcludeExample(Tag $tag)
  334. {
  335. return strpos($tag->getContent(), ' No-example') !== false;
  336. }
  337. /**
  338. * Cast a value from a string to a specified type.
  339. *
  340. * @param string $value
  341. * @param string $type
  342. *
  343. * @return mixed
  344. */
  345. private function castToType(string $value, string $type)
  346. {
  347. $casts = [
  348. 'integer' => 'intval',
  349. 'number' => 'floatval',
  350. 'float' => 'floatval',
  351. 'boolean' => 'boolval',
  352. ];
  353. // First, we handle booleans. We can't use a regular cast,
  354. //because PHP considers string 'false' as true.
  355. if ($value == 'false' && $type == 'boolean') {
  356. return false;
  357. }
  358. if (isset($casts[$type])) {
  359. return $casts[$type]($value);
  360. }
  361. return $value;
  362. }
  363. }