Generator.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. list($routeGroupName, $routeGroupDescription) = $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. 'groupName' => $routeGroupName,
  63. 'groupDescription' => $routeGroupDescription,
  64. 'title' => $docBlock['short'],
  65. 'description' => $docBlock['long'],
  66. 'methods' => $this->getMethods($route),
  67. 'uri' => $this->getUri($route),
  68. 'boundUri' => Utils::getFullUrl($route, $rulesToApply['bindings'] ?? ($rulesToApply['response_calls']['bindings'] ?? [])),
  69. 'queryParameters' => $queryParameters,
  70. 'bodyParameters' => $bodyParameters,
  71. 'cleanBodyParameters' => $this->cleanParams($bodyParameters),
  72. 'cleanQueryParameters' => $this->cleanParams($queryParameters),
  73. 'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
  74. 'response' => $content,
  75. 'showresponse' => ! empty($content),
  76. ];
  77. $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
  78. return $parsedRoute;
  79. }
  80. protected function getBodyParameters(ReflectionMethod $method, array $tags)
  81. {
  82. foreach ($method->getParameters() as $param) {
  83. $paramType = $param->getType();
  84. if ($paramType === null) {
  85. continue;
  86. }
  87. $parameterClassName = version_compare(phpversion(), '7.1.0', '<')
  88. ? $paramType->__toString()
  89. : $paramType->getName();
  90. try {
  91. $parameterClass = new ReflectionClass($parameterClassName);
  92. } catch (\ReflectionException $e) {
  93. continue;
  94. }
  95. 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)) {
  96. $formRequestDocBlock = new DocBlock($parameterClass->getDocComment());
  97. $bodyParametersFromDocBlock = $this->getBodyParametersFromDocBlock($formRequestDocBlock->getTags());
  98. if (count($bodyParametersFromDocBlock)) {
  99. return $bodyParametersFromDocBlock;
  100. }
  101. }
  102. }
  103. return $this->getBodyParametersFromDocBlock($tags);
  104. }
  105. /**
  106. * @param array $tags
  107. *
  108. * @return array
  109. */
  110. protected function getBodyParametersFromDocBlock(array $tags)
  111. {
  112. $parameters = collect($tags)
  113. ->filter(function ($tag) {
  114. return $tag instanceof Tag && $tag->getName() === 'bodyParam';
  115. })
  116. ->mapWithKeys(function ($tag) {
  117. preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $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->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. if (empty($content)) {
  184. // this means only name was supplied
  185. list($name) = preg_split('/\s+/', $tag->getContent());
  186. $required = false;
  187. $description = '';
  188. } else {
  189. list($_, $name, $required, $description) = $content;
  190. $description = trim($description);
  191. if ($description == 'required' && empty(trim($required))) {
  192. $required = $description;
  193. $description = '';
  194. }
  195. $required = trim($required) == 'required' ? true : false;
  196. }
  197. list($description, $value) = $this->parseDescription($description, 'string');
  198. if (is_null($value)) {
  199. $value = str_contains($description, ['number', 'count', 'page'])
  200. ? $this->generateDummyValue('integer')
  201. : $this->generateDummyValue('string');
  202. }
  203. return [$name => compact('description', 'required', 'value')];
  204. })->toArray();
  205. return $parameters;
  206. }
  207. /**
  208. * @param array $tags
  209. *
  210. * @return bool
  211. */
  212. protected function getAuthStatusFromDocBlock(array $tags)
  213. {
  214. $authTag = collect($tags)
  215. ->first(function ($tag) {
  216. return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
  217. });
  218. return (bool) $authTag;
  219. }
  220. /**
  221. * @param ReflectionMethod $method
  222. *
  223. * @return array
  224. */
  225. protected function parseDocBlock(ReflectionMethod $method)
  226. {
  227. $comment = $method->getDocComment();
  228. $phpdoc = new DocBlock($comment);
  229. return [
  230. 'short' => $phpdoc->getShortDescription(),
  231. 'long' => $phpdoc->getLongDescription()->getContents(),
  232. 'tags' => $phpdoc->getTags(),
  233. ];
  234. }
  235. /**
  236. * @param ReflectionClass $controller
  237. * @param ReflectionMethod $method
  238. *
  239. * @return array The route group name and description
  240. */
  241. protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
  242. {
  243. // @group tag on the method overrides that on the controller
  244. $docBlockComment = $method->getDocComment();
  245. if ($docBlockComment) {
  246. $phpdoc = new DocBlock($docBlockComment);
  247. foreach ($phpdoc->getTags() as $tag) {
  248. if ($tag->getName() === 'group') {
  249. $routeGroup = trim($tag->getContent());
  250. $routeGroupParts = explode("\n", $tag->getContent());
  251. $routeGroupName = array_shift($routeGroupParts);
  252. $routeGroupDescription = implode("\n", $routeGroupParts);
  253. return [$routeGroupName, $routeGroupDescription];
  254. }
  255. }
  256. }
  257. $docBlockComment = $controller->getDocComment();
  258. if ($docBlockComment) {
  259. $phpdoc = new DocBlock($docBlockComment);
  260. foreach ($phpdoc->getTags() as $tag) {
  261. if ($tag->getName() === 'group') {
  262. $routeGroupParts = explode("\n", $tag->getContent());
  263. $routeGroupName = array_shift($routeGroupParts);
  264. $routeGroupDescription = implode("\n", $routeGroupParts);
  265. return [$routeGroupName, $routeGroupDescription];
  266. }
  267. }
  268. }
  269. return [$this->config->get(('default_group')), ''];
  270. }
  271. private function normalizeParameterType($type)
  272. {
  273. $typeMap = [
  274. 'int' => 'integer',
  275. 'bool' => 'boolean',
  276. 'double' => 'float',
  277. ];
  278. return $type ? ($typeMap[$type] ?? $type) : 'string';
  279. }
  280. private function generateDummyValue(string $type)
  281. {
  282. $faker = Factory::create();
  283. if ($this->config->get('faker_seed')) {
  284. $faker->seed($this->config->get('faker_seed'));
  285. }
  286. $fakeFactories = [
  287. 'integer' => function () use ($faker) {
  288. return $faker->numberBetween(1, 20);
  289. },
  290. 'number' => function () use ($faker) {
  291. return $faker->randomFloat();
  292. },
  293. 'float' => function () use ($faker) {
  294. return $faker->randomFloat();
  295. },
  296. 'boolean' => function () use ($faker) {
  297. return $faker->boolean();
  298. },
  299. 'string' => function () use ($faker) {
  300. return $faker->word;
  301. },
  302. 'array' => function () {
  303. return [];
  304. },
  305. 'object' => function () {
  306. return new \stdClass;
  307. },
  308. ];
  309. $fakeFactory = $fakeFactories[$type] ?? $fakeFactories['string'];
  310. return $fakeFactory();
  311. }
  312. /**
  313. * Allows users to specify an example for the parameter by writing 'Example: the-example',
  314. * to be used in example requests and response calls.
  315. *
  316. * @param string $description
  317. * @param string $type The type of the parameter. Used to cast the example provided, if any.
  318. *
  319. * @return array The description and included example.
  320. */
  321. private function parseDescription(string $description, string $type)
  322. {
  323. $example = null;
  324. if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
  325. $description = $content[1];
  326. // examples are parsed as strings by default, we need to cast them properly
  327. $example = $this->castToType($content[2], $type);
  328. }
  329. return [$description, $example];
  330. }
  331. /**
  332. * Cast a value from a string to a specified type.
  333. *
  334. * @param string $value
  335. * @param string $type
  336. *
  337. * @return mixed
  338. */
  339. private function castToType(string $value, string $type)
  340. {
  341. $casts = [
  342. 'integer' => 'intval',
  343. 'number' => 'floatval',
  344. 'float' => 'floatval',
  345. 'boolean' => 'boolval',
  346. ];
  347. // First, we handle booleans. We can't use a regular cast,
  348. //because PHP considers string 'false' as true.
  349. if ($value == 'false' && $type == 'boolean') {
  350. return false;
  351. }
  352. if (isset($casts[$type])) {
  353. return $casts[$type]($value);
  354. }
  355. return $value;
  356. }
  357. }