AbstractGenerator.php 17 KB

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