AbstractGenerator.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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' => null,
  40. 'default' => '',
  41. 'value' => '',
  42. 'description' => [],
  43. ];
  44. foreach ($rules as $ruleName => $rule) {
  45. $this->parseRule($rule, $attribute, $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 string $ruleName
  161. * @param array $attributeData
  162. * @param int $seed
  163. *
  164. * @return void
  165. */
  166. protected function parseRule($rule, $ruleName, &$attributeData, $seed)
  167. {
  168. $faker = Factory::create();
  169. $faker->seed(crc32($seed));
  170. $parsedRule = $this->parseStringRule($rule);
  171. $parsedRule[0] = $this->normalizeRule($parsedRule[0]);
  172. list($rule, $parameters) = $parsedRule;
  173. switch ($rule) {
  174. case 'required':
  175. $attributeData['required'] = true;
  176. break;
  177. case 'accepted':
  178. $attributeData['required'] = true;
  179. $attributeData['type'] = 'boolean';
  180. $attributeData['value'] = true;
  181. break;
  182. case 'after':
  183. $attributeData['type'] = 'date';
  184. $attributeData['description'][] = Description::parse($rule)->with(date(DATE_RFC850, strtotime($parameters[0])))->getDescription();
  185. $attributeData['value'] = date(DATE_RFC850, strtotime('+1 day', strtotime($parameters[0])));
  186. break;
  187. case 'alpha':
  188. $attributeData['description'][] = Description::parse($rule)->getDescription();
  189. $attributeData['value'] = $faker->word;
  190. break;
  191. case 'alpha_dash':
  192. $attributeData['description'][] = Description::parse($rule)->getDescription();
  193. break;
  194. case 'alpha_num':
  195. $attributeData['description'][] = Description::parse($rule)->getDescription();
  196. break;
  197. case 'in':
  198. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  199. $attributeData['value'] = $faker->randomElement($parameters);
  200. break;
  201. case 'not_in':
  202. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  203. $attributeData['value'] = $faker->word;
  204. break;
  205. case 'min':
  206. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  207. break;
  208. case 'max':
  209. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  210. break;
  211. case 'between':
  212. if (! isset($attributeData['type'])) {
  213. $attributeData['type'] = 'numeric';
  214. }
  215. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  216. $attributeData['value'] = $faker->numberBetween($parameters[0], $parameters[1]);
  217. break;
  218. case 'before':
  219. $attributeData['type'] = 'date';
  220. $attributeData['description'][] = Description::parse($rule)->with(date(DATE_RFC850, strtotime($parameters[0])))->getDescription();
  221. $attributeData['value'] = date(DATE_RFC850, strtotime('-1 day', strtotime($parameters[0])));
  222. break;
  223. case 'date_format':
  224. $attributeData['type'] = 'date';
  225. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  226. $attributeData['value'] = date($parameters[0]);
  227. break;
  228. case 'different':
  229. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  230. break;
  231. case 'digits':
  232. $attributeData['type'] = 'numeric';
  233. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  234. $attributeData['value'] = $faker->randomNumber($parameters[0], true);
  235. break;
  236. case 'digits_between':
  237. $attributeData['type'] = 'numeric';
  238. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  239. break;
  240. case 'file':
  241. $attributeData['type'] = 'file';
  242. $attributeData['description'][] = Description::parse($rule)->getDescription();
  243. break;
  244. case 'image':
  245. $attributeData['type'] = 'image';
  246. $attributeData['description'][] = Description::parse($rule)->getDescription();
  247. break;
  248. case 'json':
  249. $attributeData['type'] = 'string';
  250. $attributeData['description'][] = Description::parse($rule)->getDescription();
  251. $attributeData['value'] = json_encode(['foo', 'bar', 'baz']);
  252. break;
  253. case 'mimetypes':
  254. case 'mimes':
  255. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  256. break;
  257. case 'required_if':
  258. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  259. break;
  260. case 'required_unless':
  261. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  262. break;
  263. case 'required_with':
  264. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  265. break;
  266. case 'required_with_all':
  267. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' and '))->getDescription();
  268. break;
  269. case 'required_without':
  270. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' or '))->getDescription();
  271. break;
  272. case 'required_without_all':
  273. $attributeData['description'][] = Description::parse($rule)->with($this->fancyImplode($parameters, ', ', ' and '))->getDescription();
  274. break;
  275. case 'same':
  276. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  277. break;
  278. case 'size':
  279. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  280. break;
  281. case 'timezone':
  282. $attributeData['description'][] = Description::parse($rule)->getDescription();
  283. $attributeData['value'] = $faker->timezone;
  284. break;
  285. case 'exists':
  286. $fieldName = isset($parameters[1]) ? $parameters[1] : $ruleName;
  287. $attributeData['description'][] = Description::parse($rule)->with([Str::singular($parameters[0]), $fieldName])->getDescription();
  288. break;
  289. case 'active_url':
  290. $attributeData['type'] = 'url';
  291. $attributeData['value'] = $faker->url;
  292. break;
  293. case 'regex':
  294. $attributeData['type'] = 'string';
  295. $attributeData['description'][] = Description::parse($rule)->with($parameters)->getDescription();
  296. break;
  297. case 'boolean':
  298. $attributeData['value'] = true;
  299. $attributeData['type'] = $rule;
  300. break;
  301. case 'array':
  302. $attributeData['value'] = $faker->word;
  303. $attributeData['type'] = $rule;
  304. break;
  305. case 'date':
  306. $attributeData['value'] = $faker->date();
  307. $attributeData['type'] = $rule;
  308. break;
  309. case 'email':
  310. $attributeData['value'] = $faker->safeEmail;
  311. $attributeData['type'] = $rule;
  312. break;
  313. case 'string':
  314. $attributeData['value'] = $faker->word;
  315. $attributeData['type'] = $rule;
  316. break;
  317. case 'integer':
  318. $attributeData['value'] = $faker->randomNumber();
  319. $attributeData['type'] = $rule;
  320. break;
  321. case 'numeric':
  322. $attributeData['value'] = $faker->randomNumber();
  323. $attributeData['type'] = $rule;
  324. break;
  325. case 'url':
  326. $attributeData['value'] = $faker->url;
  327. $attributeData['type'] = $rule;
  328. break;
  329. case 'ip':
  330. $attributeData['value'] = $faker->ipv4;
  331. $attributeData['type'] = $rule;
  332. break;
  333. }
  334. if ($attributeData['value'] === '') {
  335. $attributeData['value'] = $faker->word;
  336. }
  337. if (is_null($attributeData['type'])) {
  338. $attributeData['type'] = 'string';
  339. }
  340. }
  341. /**
  342. * Call the given URI and return the Response.
  343. *
  344. * @param string $method
  345. * @param string $uri
  346. * @param array $parameters
  347. * @param array $cookies
  348. * @param array $files
  349. * @param array $server
  350. * @param string $content
  351. *
  352. * @return \Illuminate\Http\Response
  353. */
  354. abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
  355. /**
  356. * Transform headers array to array of $_SERVER vars with HTTP_* format.
  357. *
  358. * @param array $headers
  359. *
  360. * @return array
  361. */
  362. protected function transformHeadersToServerVars(array $headers)
  363. {
  364. $server = [];
  365. $prefix = 'HTTP_';
  366. foreach ($headers as $name => $value) {
  367. $name = strtr(strtoupper($name), '-', '_');
  368. if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
  369. $name = $prefix.$name;
  370. }
  371. $server[$name] = $value;
  372. }
  373. return $server;
  374. }
  375. /**
  376. * Parse a string based rule.
  377. *
  378. * @param string $rules
  379. *
  380. * @return array
  381. */
  382. protected function parseStringRule($rules)
  383. {
  384. $parameters = [];
  385. // The format for specifying validation rules and parameters follows an
  386. // easy {rule}:{parameters} formatting convention. For instance the
  387. // rule "Max:3" states that the value may only be three letters.
  388. if (strpos($rules, ':') !== false) {
  389. list($rules, $parameter) = explode(':', $rules, 2);
  390. $parameters = $this->parseParameters($rules, $parameter);
  391. }
  392. return [strtolower(trim($rules)), $parameters];
  393. }
  394. /**
  395. * Parse a parameter list.
  396. *
  397. * @param string $rule
  398. * @param string $parameter
  399. *
  400. * @return array
  401. */
  402. protected function parseParameters($rule, $parameter)
  403. {
  404. if (strtolower($rule) === 'regex') {
  405. return [$parameter];
  406. }
  407. return str_getcsv($parameter);
  408. }
  409. /**
  410. * Normalizes a rule so that we can accept short types.
  411. *
  412. * @param string $rule
  413. *
  414. * @return string
  415. */
  416. protected function normalizeRule($rule)
  417. {
  418. switch ($rule) {
  419. case 'int':
  420. return 'integer';
  421. case 'bool':
  422. return 'boolean';
  423. default:
  424. return $rule;
  425. }
  426. }
  427. }