Explorer.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. <?php
  2. namespace Luracast\Restler;
  3. use stdClass;
  4. use Luracast\Restler\Data\Text;
  5. use Luracast\Restler\Data\ValidationInfo;
  6. use Luracast\Restler\Scope;
  7. /**
  8. * Class Explorer
  9. *
  10. * @package Luracast\Restler
  11. *
  12. * @access hybrid
  13. * @version 3.0.0rc6
  14. */
  15. class Explorer implements iProvideMultiVersionApi
  16. {
  17. const SWAGGER = '2.0';
  18. /**
  19. * @var array http schemes supported. http or https or both http and https
  20. */
  21. public static $schemes = array();
  22. /**
  23. * @var bool should protected resources be shown to unauthenticated users?
  24. */
  25. public static $hideProtected = true;
  26. /**
  27. * @var bool should we use format as extension?
  28. */
  29. public static $useFormatAsExtension = true;
  30. /*
  31. * @var bool can we accept scalar values (string, int, float etc) as the request body?
  32. */
  33. public static $allowScalarValueOnRequestBody = false;
  34. /**
  35. * @var array all http methods specified here will be excluded from
  36. * documentation
  37. */
  38. public static $excludedHttpMethods = array('OPTIONS');
  39. /**
  40. * @var array all paths beginning with any of the following will be excluded
  41. * from documentation
  42. */
  43. public static $excludedPaths = array();
  44. /**
  45. * @var bool
  46. */
  47. public static $placeFormatExtensionBeforeDynamicParts = true;
  48. /**
  49. * @var bool should we group all the operations with the same url or not
  50. */
  51. public static $groupOperations = false;
  52. /**
  53. * @var string class that holds metadata as static properties
  54. */
  55. public static $infoClass = 'Luracast\Restler\ExplorerInfo';
  56. /**
  57. * Injected at runtime
  58. *
  59. * @var Restler instance of restler
  60. */
  61. public $restler;
  62. /**
  63. * @var string when format is not used as the extension this property is
  64. * used to set the extension manually
  65. */
  66. public $formatString = '';
  67. /**
  68. * @var array type mapping for converting data types to JSON-Schema Draft 4
  69. * Which is followed by swagger 1.2 spec
  70. */
  71. public static $dataTypeAlias = array(
  72. //'string' => 'string',
  73. 'int' => 'integer',
  74. 'number' => 'number',
  75. 'float' => array('number', 'float'),
  76. 'bool' => 'boolean',
  77. //'boolean' => 'boolean',
  78. //'NULL' => 'null',
  79. 'array' => 'array',
  80. //'object' => 'object',
  81. 'stdClass' => 'object',
  82. 'mixed' => 'string',
  83. 'date' => array('string', 'date'),
  84. 'datetime' => array('string', 'date-time'),
  85. );
  86. /**
  87. * @var array configurable symbols to differentiate public, hybrid and
  88. * protected api
  89. */
  90. public static $apiDescriptionSuffixSymbols = array(
  91. 0 => ' 🔓', //'&nbsp; <i class="fa fa-lg fa-unlock-alt"></i>', //public api
  92. 1 => ' ◑', //'&nbsp; <i class="fa fa-lg fa-adjust"></i>', //hybrid api
  93. 2 => ' 🔐', //'&nbsp; <i class="fa fa-lg fa-lock"></i>', //protected api
  94. );
  95. protected $models = array();
  96. /**
  97. * @var bool|stdClass
  98. */
  99. protected $_fullDataRequested = false;
  100. protected $crud = array(
  101. 'POST' => 'create',
  102. 'GET' => 'retrieve',
  103. 'PUT' => 'update',
  104. 'DELETE' => 'delete',
  105. 'PATCH' => 'partial update'
  106. );
  107. protected static $prefixes = array(
  108. 'get' => 'retrieve',
  109. 'index' => 'list',
  110. 'post' => 'create',
  111. 'put' => 'update',
  112. 'patch' => 'modify',
  113. 'delete' => 'remove',
  114. );
  115. protected $_authenticated = false;
  116. protected $cacheName = '';
  117. /**
  118. * Serve static files for exploring
  119. *
  120. * Serves explorer html, css, and js files
  121. *
  122. * @url GET *
  123. */
  124. public function get()
  125. {
  126. if (func_num_args() > 1 && func_get_arg(0) == 'swagger') {
  127. /**
  128. * BUGFIX:
  129. * If we use common resourcePath (e.g. $r->addAPIClass([api-class], 'api/shop')), than we must determine resource-ID of e.g. 'api/shop'!
  130. */
  131. $arguments = func_get_args();
  132. // remove first entry
  133. array_shift($arguments);
  134. // create ID
  135. $id = implode('/', $arguments);
  136. return $this->getResources($id);
  137. }
  138. $filename = implode('/', func_get_args());
  139. $redirect = false;
  140. if (
  141. (empty($filename) && substr($_SERVER['REQUEST_URI'], -1, 1) != '/') ||
  142. $filename == 'index.html'
  143. ) {
  144. $status = 302;
  145. $url = $this->restler->getBaseUrl() . '/' . $this->base() . '/';
  146. header("{$_SERVER['SERVER_PROTOCOL']} $status " . RestException::$codes[$status]);
  147. header("Location: $url");
  148. exit;
  149. }
  150. if (
  151. isset($this->restler->responseFormat) &&
  152. $this->restler->responseFormat->getExtension() == 'js'
  153. ) {
  154. $filename .= '.js';
  155. }
  156. PassThrough::file(__DIR__ . '/explorer/' . (empty($filename) ? 'index.html' : $filename), false,
  157. 0); //60 * 60 * 24);
  158. }
  159. /**
  160. * @return stdClass
  161. */
  162. public function swagger()
  163. {
  164. $r = new stdClass();
  165. $version = (string)$this->restler->getRequestedApiVersion();
  166. $r->swagger = static::SWAGGER;
  167. $info = parse_url($this->restler->getBaseUrl());
  168. $r->host = $info['host'];
  169. if (isset($info['port'])) {
  170. $r->host .= ':' . $info['port'];
  171. }
  172. $r->basePath = isset($info['path']) ? $info['path'] : '';
  173. if (!empty(static::$schemes)) {
  174. $r->schemes = static::$schemes;
  175. }
  176. $r->produces = $this->restler->getWritableMimeTypes();
  177. $r->consumes = $this->restler->getReadableMimeTypes();
  178. $r->paths = $this->paths($version);
  179. $r->definitions = (object)$this->models;
  180. $r->securityDefinitions = $this->securityDefinitions();
  181. $r->info = compact('version') + array_filter(get_class_vars(static::$infoClass));
  182. return $r;
  183. }
  184. private function paths($version = 1)
  185. {
  186. $map = Routes::findAll(static::$excludedPaths + array($this->base()), static::$excludedHttpMethods, $version);
  187. $paths = array();
  188. foreach ($map as $path => $data) {
  189. $access = $data[0]['access'];
  190. if (static::$hideProtected && !$access) {
  191. continue;
  192. }
  193. foreach ($data as $item) {
  194. $route = $item['route'];
  195. $access = $item['access'];
  196. if (static::$hideProtected && !$access) {
  197. continue;
  198. }
  199. $url = $route['url'];
  200. $paths["/$url"][strtolower($route['httpMethod'])] = $this->operation($route);
  201. }
  202. }
  203. return $paths;
  204. }
  205. private function operation($route)
  206. {
  207. $r = new stdClass();
  208. $m = $route['metadata'];
  209. $r->operationId = $this->operationId($route);
  210. $base = strtok($route['url'], '/');
  211. if (empty($base)) {
  212. $base = 'root';
  213. }
  214. $r->tags = array($base);
  215. $r->parameters = $this->parameters($route);
  216. $r->summary = isset($m['description'])
  217. ? $m['description']
  218. : '';
  219. $r->summary .= $route['accessLevel'] > 2
  220. ? static::$apiDescriptionSuffixSymbols[2]
  221. : static::$apiDescriptionSuffixSymbols[$route['accessLevel']];
  222. $r->description = isset($m['longDescription'])
  223. ? $m['longDescription']
  224. : '';
  225. $r->responses = $this->responses($route);
  226. //TODO: avoid hard coding. Properly detect security
  227. if ($route['accessLevel']) {
  228. $r->security = array(array('api_key' => array()));
  229. }
  230. /*
  231. $this->setType(
  232. $r,
  233. new ValidationInfo(Util::nestedValue($m, 'return') ?: array())
  234. );
  235. if (is_null($r->type) || 'mixed' == $r->type) {
  236. $r->type = 'array';
  237. } elseif ($r->type == 'null') {
  238. $r->type = 'void';
  239. } elseif (Text::contains($r->type, '|')) {
  240. $r->type = 'array';
  241. }
  242. */
  243. //TODO: add $r->authorizations
  244. //A list of authorizations required to execute this operation. While not mandatory, if used, it overrides
  245. //the value given at the API Declaration's authorizations. In order to completely remove API Declaration's
  246. //authorizations completely, an empty object ({}) may be applied.
  247. //TODO: add $r->produces
  248. //TODO: add $r->consumes
  249. //A list of MIME types this operation can produce/consume. This is overrides the global produces definition at the root of the API Declaration. Each string value SHOULD represent a MIME type.
  250. //TODO: add $r->deprecated
  251. //Declares this operation to be deprecated. Usage of the declared operation should be refrained. Valid value MUST be either "true" or "false". Note: This field will change to type boolean in the future.
  252. return $r;
  253. }
  254. private function parameters(array $route)
  255. {
  256. $r = array();
  257. $children = array();
  258. $required = false;
  259. foreach ($route['metadata']['param'] as $param) {
  260. $info = new ValidationInfo($param);
  261. $description = isset($param['description']) ? $param['description'] : '';
  262. if ('body' == $info->from) {
  263. if ($info->required) {
  264. $required = true;
  265. }
  266. $param['description'] = $description;
  267. $children[] = $param;
  268. } else {
  269. $r[] = $this->parameter($info, $description);
  270. }
  271. }
  272. if (!empty($children)) {
  273. if (
  274. 1 == count($children) &&
  275. (static::$allowScalarValueOnRequestBody || !empty($children[0]['children']))
  276. ) {
  277. $firstChild = $children[0];
  278. if (empty($firstChild['children'])) {
  279. $description = $firstChild['description'];
  280. } else {
  281. $description = ''; //'<section class="body-param">';
  282. foreach ($firstChild['children'] as $child) {
  283. $description .= isset($child['required']) && $child['required']
  284. ? '**' . $child['name'] . '** (required) '.PHP_EOL
  285. : $child['name'] . ' '.PHP_EOL;
  286. }
  287. //$description .= '</section>';
  288. }
  289. $r[] = $this->parameter(new ValidationInfo($firstChild), $description);
  290. } else {
  291. $description = ''; //'<section class="body-param">';
  292. foreach ($children as $child) {
  293. $description .= isset($child['required']) && $child['required']
  294. ? '**' . $child['name'] . '** (required) '.PHP_EOL
  295. : $child['name'] . ' '.PHP_EOL;
  296. }
  297. //$description .= '</section>';
  298. //lets group all body parameters under a generated model name
  299. $name = $this->modelName($route);
  300. $r[] = $this->parameter(
  301. new ValidationInfo(array(
  302. 'name' => $name,
  303. 'type' => $name,
  304. 'from' => 'body',
  305. 'required' => $required,
  306. 'children' => $children
  307. )),
  308. $description
  309. );
  310. }
  311. }
  312. return $r;
  313. }
  314. private function parameter(ValidationInfo $info, $description = '')
  315. {
  316. $p = new stdClass();
  317. if (isset($info->rules['model'])) {
  318. //$info->type = $info->rules['model'];
  319. }
  320. $p->name = $info->name;
  321. $this->setType($p, $info);
  322. if (empty($info->children) || $info->type != 'array') {
  323. //primitives
  324. if ($info->default) {
  325. $p->defaultValue = $info->default;
  326. }
  327. if ($info->choice) {
  328. $p->enum = $info->choice;
  329. }
  330. if ($info->min) {
  331. $p->minimum = $info->min;
  332. }
  333. if ($info->max) {
  334. $p->maximum = $info->max;
  335. }
  336. //TODO: $p->items and $p->uniqueItems boolean
  337. }
  338. $p->description = $description;
  339. $p->in = $info->from; //$info->from == 'body' ? 'form' : $info->from;
  340. $p->required = $info->required;
  341. //$p->allowMultiple = false;
  342. if (isset($p->{'$ref'})) {
  343. $p->schema = (object)array('$ref' => ($p->{'$ref'}));
  344. unset($p->{'$ref'});
  345. }
  346. return $p;
  347. }
  348. private function responses(array $route)
  349. {
  350. $code = '200';
  351. $r = array(
  352. $code => (object)array(
  353. 'description' => 'Success',
  354. 'schema' => new stdClass()
  355. )
  356. );
  357. $return = Util::nestedValue($route, 'metadata', 'return');
  358. if (!empty($return)) {
  359. $this->setType($r[$code]->schema, new ValidationInfo($return));
  360. }
  361. if (is_array($throws = Util::nestedValue($route, 'metadata', 'throws'))) {
  362. foreach ($throws as $message) {
  363. $r[$message['code']] = array('description' => $message['message']);
  364. }
  365. }
  366. return $r;
  367. }
  368. private function model($type, array $children)
  369. {
  370. if (isset($this->models[$type])) {
  371. return $this->models[$type];
  372. }
  373. $r = new stdClass();
  374. $r->properties = array();
  375. $required = array();
  376. foreach ($children as $child) {
  377. $info = new ValidationInfo($child);
  378. $p = new stdClass();
  379. $this->setType($p, $info);
  380. $p->description = isset($child['description']) ? $child['description'] : '';
  381. if ($info->default) {
  382. $p->defaultValue = $info->default;
  383. }
  384. if ($info->choice) {
  385. $p->enum = $info->choice;
  386. }
  387. if ($info->min) {
  388. $p->minimum = $info->min;
  389. }
  390. if ($info->max) {
  391. $p->maximum = $info->max;
  392. }
  393. if ($info->required) {
  394. $required[] = $info->name;
  395. }
  396. $r->properties[$info->name] = $p;
  397. }
  398. if (!empty($required)) {
  399. $r->required = $required;
  400. }
  401. //TODO: add $r->subTypes https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md#527-model-object
  402. //TODO: add $r->discriminator https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md#527-model-object
  403. $this->models[$type] = $r;
  404. return $r;
  405. }
  406. private function setType(&$object, ValidationInfo $info)
  407. {
  408. //TODO: proper type management
  409. $type = Util::getShortName($info->type);
  410. if ($info->type == 'array') {
  411. $object->type = 'array';
  412. if ($info->children) {
  413. $contentType = Util::getShortName($info->contentType);
  414. $model = $this->model($contentType, $info->children);
  415. $object->items = (object)array(
  416. '$ref' => "#/definitions/$contentType"
  417. );
  418. } elseif ($info->contentType && $info->contentType == 'associative') {
  419. unset($info->contentType);
  420. $this->model($info->type = 'Object', array(
  421. array(
  422. 'name' => 'property',
  423. 'type' => 'string',
  424. 'default' => '',
  425. 'required' => false,
  426. 'description' => ''
  427. )
  428. ));
  429. } elseif ($info->contentType && $info->contentType != 'indexed') {
  430. if (is_string($info->contentType) && $t = Util::nestedValue(static::$dataTypeAlias,
  431. strtolower($info->contentType))) {
  432. if (is_array($t)) {
  433. $object->items = (object)array(
  434. 'type' => $t[0],
  435. 'format' => $t[1],
  436. );
  437. } else {
  438. $object->items = (object)array(
  439. 'type' => $t,
  440. );
  441. }
  442. } else {
  443. $contentType = Util::getShortName($info->contentType);
  444. $object->items = (object)array(
  445. '$ref' => "#/definitions/$contentType"
  446. );
  447. }
  448. } else {
  449. $object->items = (object)array(
  450. 'type' => 'string'
  451. );
  452. }
  453. } elseif ($info->children) {
  454. $this->model($type, $info->children);
  455. $object->{'$ref'} = "#/definitions/$type";
  456. } elseif (is_string($info->type) && $t = Util::nestedValue(static::$dataTypeAlias, strtolower($info->type))) {
  457. if (is_array($t)) {
  458. $object->type = $t[0];
  459. $object->format = $t[1];
  460. } else {
  461. $object->type = $t;
  462. }
  463. } else {
  464. $object->type = 'string';
  465. }
  466. $has64bit = PHP_INT_MAX > 2147483647;
  467. if (isset($object->type)) {
  468. if ($object->type == 'integer') {
  469. $object->format = $has64bit
  470. ? 'int64'
  471. : 'int32';
  472. } elseif ($object->type == 'number') {
  473. $object->format = $has64bit
  474. ? 'double'
  475. : 'float';
  476. }
  477. }
  478. }
  479. private function operationId(array $route)
  480. {
  481. static $hash = array();
  482. $id = $route['httpMethod'] . ' ' . $route['url'];
  483. if (isset($hash[$id])) {
  484. return $hash[$id];
  485. }
  486. $class = Util::getShortName($route['className']);
  487. $method = $route['methodName'];
  488. if (isset(static::$prefixes[$method])) {
  489. $method = static::$prefixes[$method] . $class;
  490. } else {
  491. $method = str_replace(
  492. array_keys(static::$prefixes),
  493. array_values(static::$prefixes),
  494. $method
  495. );
  496. $method = lcfirst($class) . ucfirst($method);
  497. }
  498. $hash[$id] = $method;
  499. return $method;
  500. }
  501. private function modelName(array $route)
  502. {
  503. return $this->operationId($route) . 'Model';
  504. }
  505. private function securityDefinitions()
  506. {
  507. $r = new stdClass();
  508. $r->api_key = (object)array(
  509. 'type' => 'apiKey',
  510. 'name' => 'api_key',
  511. 'in' => 'query',
  512. );
  513. return $r;
  514. }
  515. private function base()
  516. {
  517. return strtok($this->restler->url, '/');
  518. }
  519. /**
  520. * Maximum api version supported by the api class
  521. * @return int
  522. */
  523. public static function __getMaximumSupportedVersion()
  524. {
  525. return Scope::get('Restler')->getApiVersion();
  526. }
  527. }