AbstractGenerator.php 15 KB

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