AbstractGenerator.php 18 KB

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