Generator.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 string The seed to be used with Faker.
  15. * Useful when you want to always have the same fake output.
  16. */
  17. private $fakerSeed = null;
  18. public function __construct(string $fakerSeed = null)
  19. {
  20. $this->fakerSeed = $fakerSeed;
  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. $routeAction = $route->getAction();
  49. list($class, $method) = explode('@', $routeAction['uses']);
  50. $controller = new ReflectionClass($class);
  51. $method = $controller->getMethod($method);
  52. $routeGroup = $this->getRouteGroup($controller, $method);
  53. $docBlock = $this->parseDocBlock($method);
  54. $bodyParameters = $this->getBodyParameters($method, $docBlock['tags']);
  55. $queryParameters = $this->getQueryParametersFromDocBlock($docBlock['tags']);
  56. $content = ResponseResolver::getResponse($route, $docBlock['tags'], [
  57. 'rules' => $rulesToApply,
  58. 'body' => $bodyParameters,
  59. 'query' => $queryParameters,
  60. ]);
  61. $parsedRoute = [
  62. 'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
  63. 'group' => $routeGroup,
  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'] ?? []),
  69. 'bodyParameters' => $bodyParameters,
  70. 'cleanBodyParameters' => $this->cleanParams($bodyParameters),
  71. 'queryParameters' => $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)) {
  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. if (empty($content)) {
  118. // this means only name and type were supplied
  119. list($name, $type) = preg_split('/\s+/', $tag->getContent());
  120. $required = false;
  121. $description = '';
  122. } else {
  123. list($_, $name, $type, $required, $description) = $content;
  124. $description = trim($description);
  125. if ($description == 'required' && empty(trim($required))) {
  126. $required = $description;
  127. $description = '';
  128. }
  129. $required = trim($required) == 'required' ? true : false;
  130. }
  131. $type = $this->normalizeParameterType($type);
  132. list($description, $example) = $this->parseDescription($description, $type);
  133. $value = is_null($example) ? $this->generateDummyValue($type) : $example;
  134. return [$name => compact('type', 'description', 'required', 'value')];
  135. })->toArray();
  136. return $parameters;
  137. }
  138. /**
  139. * @param array $tags
  140. *
  141. * @return array
  142. */
  143. protected function getQueryParametersFromDocBlock(array $tags)
  144. {
  145. $parameters = collect($tags)
  146. ->filter(function ($tag) {
  147. return $tag instanceof Tag && $tag->getName() === 'queryParam';
  148. })
  149. ->mapWithKeys(function ($tag) {
  150. preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
  151. if (empty($content)) {
  152. // this means only name was supplied
  153. list($name) = preg_split('/\s+/', $tag->getContent());
  154. $required = false;
  155. $description = '';
  156. } else {
  157. list($_, $name, $required, $description) = $content;
  158. $description = trim($description);
  159. if ($description == 'required' && empty(trim($required))) {
  160. $required = $description;
  161. $description = '';
  162. }
  163. $required = trim($required) == 'required' ? true : false;
  164. }
  165. list($description, $value) = $this->parseDescription($description, 'string');
  166. if (is_null($value)) {
  167. $value = str_contains($description, ['number', 'count', 'page'])
  168. ? $this->generateDummyValue('integer')
  169. : $this->generateDummyValue('string');
  170. }
  171. return [$name => compact('description', 'required', 'value')];
  172. })->toArray();
  173. return $parameters;
  174. }
  175. /**
  176. * @param array $tags
  177. *
  178. * @return bool
  179. */
  180. protected function getAuthStatusFromDocBlock(array $tags)
  181. {
  182. $authTag = collect($tags)
  183. ->first(function ($tag) {
  184. return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
  185. });
  186. return (bool) $authTag;
  187. }
  188. /**
  189. * @param ReflectionMethod $method
  190. *
  191. * @return array
  192. */
  193. protected function parseDocBlock(ReflectionMethod $method)
  194. {
  195. $comment = $method->getDocComment();
  196. $phpdoc = new DocBlock($comment);
  197. return [
  198. 'short' => $phpdoc->getShortDescription(),
  199. 'long' => $phpdoc->getLongDescription()->getContents(),
  200. 'tags' => $phpdoc->getTags(),
  201. ];
  202. }
  203. /**
  204. * @param ReflectionClass $controller
  205. * @param ReflectionMethod $method
  206. *
  207. * @return string
  208. */
  209. protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
  210. {
  211. // @group tag on the method overrides that on the controller
  212. $docBlockComment = $method->getDocComment();
  213. if ($docBlockComment) {
  214. $phpdoc = new DocBlock($docBlockComment);
  215. foreach ($phpdoc->getTags() as $tag) {
  216. if ($tag->getName() === 'group') {
  217. return $tag->getContent();
  218. }
  219. }
  220. }
  221. $docBlockComment = $controller->getDocComment();
  222. if ($docBlockComment) {
  223. $phpdoc = new DocBlock($docBlockComment);
  224. foreach ($phpdoc->getTags() as $tag) {
  225. if ($tag->getName() === 'group') {
  226. return $tag->getContent();
  227. }
  228. }
  229. }
  230. return config('apidoc.ungrouped_name') ?: 'general';
  231. }
  232. private function normalizeParameterType($type)
  233. {
  234. $typeMap = [
  235. 'int' => 'integer',
  236. 'bool' => 'boolean',
  237. 'double' => 'float',
  238. ];
  239. return $type ? ($typeMap[$type] ?? $type) : 'string';
  240. }
  241. private function generateDummyValue(string $type)
  242. {
  243. $faker = Factory::create();
  244. if ($this->fakerSeed) {
  245. $faker->seed($this->fakerSeed);
  246. }
  247. $fakes = [
  248. 'integer' => function () use ($faker) {
  249. return $faker->numberBetween(1, 20);
  250. },
  251. 'number' => function () use ($faker) {
  252. return $faker->randomFloat();
  253. },
  254. 'float' => function () use ($faker) {
  255. return $faker->randomFloat();
  256. },
  257. 'boolean' => function () use ($faker) {
  258. return $faker->boolean();
  259. },
  260. 'string' => function () use ($faker) {
  261. return $faker->word;
  262. },
  263. 'array' => function () {
  264. return [];
  265. },
  266. 'object' => function () {
  267. return new \stdClass;
  268. },
  269. ];
  270. $fake = $fakes[$type] ?? $fakes['string'];
  271. return $fake();
  272. }
  273. /**
  274. * Allows users to specify an example for the parameter by writing 'Example: the-example',
  275. * to be used in example requests and response calls.
  276. *
  277. * @param string $description
  278. * @param string $type The type of the parameter. Used to cast the example provided, if any.
  279. *
  280. * @return array The description and included example.
  281. */
  282. private function parseDescription(string $description, string $type)
  283. {
  284. $example = null;
  285. if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
  286. $description = $content[1];
  287. // examples are parsed as strings by default, we need to cast them properly
  288. $example = $this->castToType($content[2], $type);
  289. }
  290. return [$description, $example];
  291. }
  292. /**
  293. * Cast a value from a string to a specified type.
  294. *
  295. * @param string $value
  296. * @param string $type
  297. *
  298. * @return mixed
  299. */
  300. private function castToType(string $value, string $type)
  301. {
  302. $casts = [
  303. 'integer' => 'intval',
  304. 'number' => 'floatval',
  305. 'float' => 'floatval',
  306. 'boolean' => 'boolval',
  307. ];
  308. // First, we handle booleans. We can't use a regular cast,
  309. //because PHP considers string 'false' as true.
  310. if ($value == 'false' && $type == 'boolean') {
  311. return false;
  312. }
  313. if (isset($casts[$type])) {
  314. return $casts[$type]($value);
  315. }
  316. return $value;
  317. }
  318. }