AbstractGenerator.php 24 KB

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