AbstractGenerator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. namespace Mpociot\ApiDoc\Generators;
  3. use Faker\Factory;
  4. use Illuminate\Foundation\Http\FormRequest;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Support\Str;
  7. use Mpociot\ApiDoc\Parsers\RuleDescriptionParser as Description;
  8. use ReflectionClass;
  9. use Mpociot\Reflection\DocBlock;
  10. abstract class AbstractGenerator
  11. {
  12. /**
  13. * @param $route
  14. *
  15. * @return mixed
  16. */
  17. abstract protected function getUri($route);
  18. /**
  19. * @param \Illuminate\Routing\Route $route
  20. * @param array $bindings
  21. * @param bool $withResponse
  22. *
  23. * @return array
  24. */
  25. abstract public function processRoute($route, $bindings = [], $withResponse = true);
  26. /**
  27. * @param array $routeData
  28. * @param array $routeAction
  29. * @param array $bindings
  30. *
  31. * @return mixed
  32. */
  33. protected function getParameters($routeData, $routeAction, $bindings)
  34. {
  35. $validator = Validator::make([], $this->getRouteRules($routeAction['uses'], $bindings));
  36. foreach ($validator->getRules() as $attribute => $rules) {
  37. $attributeData = [
  38. 'required' => false,
  39. 'type' => 'string',
  40. 'default' => '',
  41. 'value' => '',
  42. 'description' => [],
  43. ];
  44. foreach ($rules as $rule) {
  45. $this->parseRule($rule, $attributeData, $routeData['id']);
  46. }
  47. $routeData['parameters'][$attribute] = $attributeData;
  48. }
  49. return $routeData;
  50. }
  51. /**
  52. * @param $route
  53. *
  54. * @return \Illuminate\Http\Response
  55. */
  56. protected function getRouteResponse($route, $bindings)
  57. {
  58. $uri = $this->addRouteModelBindings($route, $bindings);
  59. $methods = $route->getMethods();
  60. return $this->callRoute(array_shift($methods), $uri);
  61. }
  62. /**
  63. * @param $route
  64. * @param array $bindings
  65. *
  66. * @return mixed
  67. */
  68. protected function addRouteModelBindings($route, $bindings)
  69. {
  70. $uri = $this->getUri($route);
  71. foreach ($bindings as $model => $id) {
  72. $uri = str_replace('{'.$model.'}', $id, $uri);
  73. }
  74. return $uri;
  75. }
  76. /**
  77. * @param \Illuminate\Routing\Route $route
  78. *
  79. * @return string
  80. */
  81. protected function getRouteDescription($route)
  82. {
  83. list($class, $method) = explode('@', $route);
  84. $reflection = new ReflectionClass($class);
  85. $reflectionMethod = $reflection->getMethod($method);
  86. $comment = $reflectionMethod->getDocComment();
  87. $phpdoc = new DocBlock($comment);
  88. return [
  89. 'short' => $phpdoc->getShortDescription(),
  90. 'long' => $phpdoc->getLongDescription()->getContents(),
  91. ];
  92. }
  93. /**
  94. * @param string $route
  95. *
  96. * @return string
  97. */
  98. protected function getRouteGroup($route)
  99. {
  100. list($class, $method) = explode('@', $route);
  101. $reflection = new ReflectionClass($class);
  102. $comment = $reflection->getDocComment();
  103. if ($comment) {
  104. $phpdoc = new DocBlock($comment);
  105. foreach ($phpdoc->getTags() as $tag) {
  106. if ($tag->getName() === 'resource') {
  107. return $tag->getContent();
  108. }
  109. }
  110. }
  111. return 'general';
  112. }
  113. /**
  114. * @param $route
  115. * @param array $bindings
  116. *
  117. * @return array
  118. */
  119. protected function getRouteRules($route, $bindings)
  120. {
  121. list($class, $method) = explode('@', $route);
  122. $reflection = new ReflectionClass($class);
  123. $reflectionMethod = $reflection->getMethod($method);
  124. foreach ($reflectionMethod->getParameters() as $parameter) {
  125. $parameterType = $parameter->getClass();
  126. if (! is_null($parameterType) && class_exists($parameterType->name)) {
  127. $className = $parameterType->name;
  128. if (is_subclass_of($className, FormRequest::class)) {
  129. $parameterReflection = new $className;
  130. // Add route parameter bindings
  131. $parameterReflection->query->add($bindings);
  132. $parameterReflection->request->add($bindings);
  133. if (method_exists($parameterReflection, 'validator')) {
  134. return $parameterReflection->validator()->getRules();
  135. } else {
  136. return $parameterReflection->rules();
  137. }
  138. }
  139. }
  140. }
  141. return [];
  142. }
  143. /**
  144. * @param array $arr
  145. * @param string $first
  146. * @param string $last
  147. *
  148. * @return string
  149. */
  150. protected function fancyImplode($arr, $first, $last)
  151. {
  152. $arr = array_map(function ($value) {
  153. return '`'.$value.'`';
  154. }, $arr);
  155. array_push($arr, implode($last, array_splice($arr, -2)));
  156. return implode($first, $arr);
  157. }
  158. /**
  159. * @param string $rule
  160. * @param array $attributeData
  161. *
  162. * @return void
  163. */
  164. protected function parseRule($rule, &$attributeData, $seed)
  165. {
  166. $faker = Factory::create();
  167. $faker->seed(crc32($seed));
  168. $parsedRule = $this->parseStringRule($rule);
  169. $parsedRule[0] = $this->normalizeRule($parsedRule[0]);
  170. list($rule, $parameters) = $parsedRule;
  171. switch ($rule) {
  172. case 'required':
  173. $attributeData['required'] = true;
  174. break;
  175. case 'accepted':
  176. $attributeData['required'] = true;
  177. $attributeData['type'] = 'boolean';
  178. $attributeData['value'] = true;
  179. break;
  180. case 'after':
  181. $attributeData['type'] = 'date';
  182. $attributeData['description'][] = Description::parse($rule)->with(date(DATE_RFC850, strtotime($parameters[0])))->getDescription();
  183. $attributeData['value'] = date(DATE_RFC850, strtotime('+1 day', strtotime($parameters[0])));
  184. break;
  185. case 'alpha':
  186. $attributeData['description'][] = Description::parse($rule)->getDescription();
  187. $attributeData['value'] = $faker->word;
  188. break;
  189. case 'alpha_dash':
  190. $attributeData['description'][] = Description::parse($rule)->getDescription();
  191. break;
  192. case 'alpha_num':
  193. $attributeData['description'][] = Description::parse($rule)->getDescription();
  194. break;
  195. case 'in':
  196. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  197. $attributeData['value'] = $faker->randomElement($parameters);
  198. break;
  199. case 'not_in':
  200. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  201. $attributeData['value'] = $faker->word;
  202. break;
  203. case 'min':
  204. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  205. break;
  206. case 'max':
  207. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  208. break;
  209. case 'between':
  210. $attributeData['type'] = 'numeric';
  211. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  212. $attributeData['value'] = $faker->numberBetween($parameters[0], $parameters[1]);
  213. break;
  214. case 'before':
  215. $attributeData['type'] = 'date';
  216. $attributeData['description'][] = Description::parse($rule)->with(date(DATE_RFC850, strtotime($parameters[0])))->getDescription();
  217. $attributeData['value'] = date(DATE_RFC850, strtotime('-1 day', strtotime($parameters[0])));
  218. break;
  219. case 'date_format':
  220. $attributeData['type'] = 'date';
  221. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  222. break;
  223. case 'different':
  224. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  225. break;
  226. case 'digits':
  227. $attributeData['type'] = 'numeric';
  228. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  229. $attributeData['value'] = $faker->randomNumber($parameters[0], true);
  230. break;
  231. case 'digits_between':
  232. $attributeData['type'] = 'numeric';
  233. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  234. break;
  235. case 'image':
  236. $attributeData['type'] = 'image';
  237. $attributeData['description'][] = Description::parse($rule)->getDescription();
  238. break;
  239. case 'json':
  240. $attributeData['type'] = 'string';
  241. $attributeData['description'][] = Description::parse($rule)->getDescription();
  242. $attributeData['value'] = json_encode(['foo', 'bar', 'baz']);
  243. break;
  244. case 'mimetypes':
  245. case 'mimes':
  246. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  247. break;
  248. case 'required_if':
  249. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  250. break;
  251. case 'required_unless':
  252. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  253. break;
  254. case 'required_with':
  255. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  256. break;
  257. case 'required_with_all':
  258. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' and '))->getDescription();
  259. break;
  260. case 'required_without':
  261. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  262. break;
  263. case 'required_without_all':
  264. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' and '))->getDescription();
  265. break;
  266. case 'same':
  267. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  268. break;
  269. case 'size':
  270. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  271. break;
  272. case 'timezone':
  273. $attributeData['description'][] = Description::parse($rule)->getDescription();
  274. $attributeData['value'] = $faker->timezone;
  275. break;
  276. case 'exists':
  277. $attributeData['description'][] = Description::parse($rule)->with([Str::singular($parameters[0]), $parameters[1]])->getDescription();
  278. break;
  279. case 'active_url':
  280. $attributeData['type'] = 'url';
  281. $attributeData['value'] = $faker->url;
  282. break;
  283. case 'regex':
  284. $attributeData['type'] = 'string';
  285. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  286. break;
  287. case 'boolean':
  288. $attributeData['value'] = true;
  289. $attributeData['type'] = $rule;
  290. break;
  291. case 'array':
  292. $attributeData['value'] = $faker->word;
  293. $attributeData['type'] = $rule;
  294. break;
  295. case 'date':
  296. $attributeData['value'] = $faker->date();
  297. $attributeData['type'] = $rule;
  298. break;
  299. case 'email':
  300. $attributeData['value'] = $faker->safeEmail;
  301. $attributeData['type'] = $rule;
  302. break;
  303. case 'string':
  304. $attributeData['value'] = $faker->word;
  305. $attributeData['type'] = $rule;
  306. break;
  307. case 'integer':
  308. $attributeData['value'] = $faker->randomNumber();
  309. $attributeData['type'] = $rule;
  310. break;
  311. case 'numeric':
  312. $attributeData['value'] = $faker->randomNumber();
  313. $attributeData['type'] = $rule;
  314. break;
  315. case 'url':
  316. $attributeData['value'] = $faker->url;
  317. $attributeData['type'] = $rule;
  318. break;
  319. case 'ip':
  320. $attributeData['value'] = $faker->ipv4;
  321. $attributeData['type'] = $rule;
  322. break;
  323. }
  324. if ($attributeData['value'] === '') {
  325. $attributeData['value'] = $faker->word;
  326. }
  327. }
  328. /**
  329. * Call the given URI and return the Response.
  330. *
  331. * @param string $method
  332. * @param string $uri
  333. * @param array $parameters
  334. * @param array $cookies
  335. * @param array $files
  336. * @param array $server
  337. * @param string $content
  338. *
  339. * @return \Illuminate\Http\Response
  340. */
  341. abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
  342. /**
  343. * Transform headers array to array of $_SERVER vars with HTTP_* format.
  344. *
  345. * @param array $headers
  346. *
  347. * @return array
  348. */
  349. protected function transformHeadersToServerVars(array $headers)
  350. {
  351. $server = [];
  352. $prefix = 'HTTP_';
  353. foreach ($headers as $name => $value) {
  354. $name = strtr(strtoupper($name), '-', '_');
  355. if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
  356. $name = $prefix.$name;
  357. }
  358. $server[$name] = $value;
  359. }
  360. return $server;
  361. }
  362. /**
  363. * Parse a string based rule.
  364. *
  365. * @param string $rules
  366. *
  367. * @return array
  368. */
  369. protected function parseStringRule($rules)
  370. {
  371. $parameters = [];
  372. // The format for specifying validation rules and parameters follows an
  373. // easy {rule}:{parameters} formatting convention. For instance the
  374. // rule "Max:3" states that the value may only be three letters.
  375. if (strpos($rules, ':') !== false) {
  376. list($rules, $parameter) = explode(':', $rules, 2);
  377. $parameters = $this->parseParameters($rules, $parameter);
  378. }
  379. return [strtolower(trim($rules)), $parameters];
  380. }
  381. /**
  382. * Parse a parameter list.
  383. *
  384. * @param string $rule
  385. * @param string $parameter
  386. *
  387. * @return array
  388. */
  389. protected function parseParameters($rule, $parameter)
  390. {
  391. if (strtolower($rule) === 'regex') {
  392. return [$parameter];
  393. }
  394. return str_getcsv($parameter);
  395. }
  396. /**
  397. * Normalizes a rule so that we can accept short types.
  398. *
  399. * @param string $rule
  400. *
  401. * @return string
  402. */
  403. protected function normalizeRule($rule)
  404. {
  405. switch ($rule) {
  406. case 'int':
  407. return 'integer';
  408. case 'bool':
  409. return 'boolean';
  410. default:
  411. return $rule;
  412. }
  413. }
  414. }