AbstractGenerator.php 20 KB

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