No Description

Uri.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. <?php
  2. namespace GuzzleHttp\Psr7;
  3. use Psr\Http\Message\UriInterface;
  4. /**
  5. * Basic PSR-7 URI implementation.
  6. *
  7. * @link https://github.com/phly/http This class is based upon
  8. * Matthew Weier O'Phinney's URI implementation in phly/http.
  9. */
  10. class Uri implements UriInterface
  11. {
  12. private static $schemes = [
  13. 'http' => 80,
  14. 'https' => 443,
  15. ];
  16. private static $charUnreserved = 'a-zA-Z0-9_\-\.~';
  17. private static $charSubDelims = '!\$&\'\(\)\*\+,;=';
  18. private static $replaceQuery = ['=' => '%3D', '&' => '%26'];
  19. /** @var string Uri scheme. */
  20. private $scheme = '';
  21. /** @var string Uri user info. */
  22. private $userInfo = '';
  23. /** @var string Uri host. */
  24. private $host = '';
  25. /** @var int|null Uri port. */
  26. private $port;
  27. /** @var string Uri path. */
  28. private $path = '';
  29. /** @var string Uri query string. */
  30. private $query = '';
  31. /** @var string Uri fragment. */
  32. private $fragment = '';
  33. /**
  34. * @param string $uri URI to parse and wrap.
  35. */
  36. public function __construct($uri = '')
  37. {
  38. if ($uri != null) {
  39. $parts = parse_url($uri);
  40. if ($parts === false) {
  41. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  42. }
  43. $this->applyParts($parts);
  44. }
  45. }
  46. public function __toString()
  47. {
  48. return self::createUriString(
  49. $this->scheme,
  50. $this->getAuthority(),
  51. $this->getPath(),
  52. $this->query,
  53. $this->fragment
  54. );
  55. }
  56. /**
  57. * Removes dot segments from a path and returns the new path.
  58. *
  59. * @param string $path
  60. *
  61. * @return string
  62. * @link http://tools.ietf.org/html/rfc3986#section-5.2.4
  63. */
  64. public static function removeDotSegments($path)
  65. {
  66. static $noopPaths = ['' => true, '/' => true, '*' => true];
  67. static $ignoreSegments = ['.' => true, '..' => true];
  68. if (isset($noopPaths[$path])) {
  69. return $path;
  70. }
  71. $results = [];
  72. $segments = explode('/', $path);
  73. foreach ($segments as $segment) {
  74. if ($segment == '..') {
  75. array_pop($results);
  76. } elseif (!isset($ignoreSegments[$segment])) {
  77. $results[] = $segment;
  78. }
  79. }
  80. $newPath = implode('/', $results);
  81. // Add the leading slash if necessary
  82. if (substr($path, 0, 1) === '/' &&
  83. substr($newPath, 0, 1) !== '/'
  84. ) {
  85. $newPath = '/' . $newPath;
  86. }
  87. // Add the trailing slash if necessary
  88. if ($newPath != '/' && isset($ignoreSegments[end($segments)])) {
  89. $newPath .= '/';
  90. }
  91. return $newPath;
  92. }
  93. /**
  94. * Resolve a base URI with a relative URI and return a new URI.
  95. *
  96. * @param UriInterface $base Base URI
  97. * @param string $rel Relative URI
  98. *
  99. * @return UriInterface
  100. */
  101. public static function resolve(UriInterface $base, $rel)
  102. {
  103. if ($rel === null || $rel === '') {
  104. return $base;
  105. }
  106. if (!($rel instanceof UriInterface)) {
  107. $rel = new self($rel);
  108. }
  109. // Return the relative uri as-is if it has a scheme.
  110. if ($rel->getScheme()) {
  111. return $rel->withPath(static::removeDotSegments($rel->getPath()));
  112. }
  113. $relParts = [
  114. 'scheme' => $rel->getScheme(),
  115. 'authority' => $rel->getAuthority(),
  116. 'path' => $rel->getPath(),
  117. 'query' => $rel->getQuery(),
  118. 'fragment' => $rel->getFragment()
  119. ];
  120. $parts = [
  121. 'scheme' => $base->getScheme(),
  122. 'authority' => $base->getAuthority(),
  123. 'path' => $base->getPath(),
  124. 'query' => $base->getQuery(),
  125. 'fragment' => $base->getFragment()
  126. ];
  127. if (!empty($relParts['authority'])) {
  128. $parts['authority'] = $relParts['authority'];
  129. $parts['path'] = self::removeDotSegments($relParts['path']);
  130. $parts['query'] = $relParts['query'];
  131. $parts['fragment'] = $relParts['fragment'];
  132. } elseif (!empty($relParts['path'])) {
  133. if (substr($relParts['path'], 0, 1) == '/') {
  134. $parts['path'] = self::removeDotSegments($relParts['path']);
  135. $parts['query'] = $relParts['query'];
  136. $parts['fragment'] = $relParts['fragment'];
  137. } else {
  138. if (!empty($parts['authority']) && empty($parts['path'])) {
  139. $mergedPath = '/';
  140. } else {
  141. $mergedPath = substr($parts['path'], 0, strrpos($parts['path'], '/') + 1);
  142. }
  143. $parts['path'] = self::removeDotSegments($mergedPath . $relParts['path']);
  144. $parts['query'] = $relParts['query'];
  145. $parts['fragment'] = $relParts['fragment'];
  146. }
  147. } elseif (!empty($relParts['query'])) {
  148. $parts['query'] = $relParts['query'];
  149. } elseif ($relParts['fragment'] != null) {
  150. $parts['fragment'] = $relParts['fragment'];
  151. }
  152. return new self(static::createUriString(
  153. $parts['scheme'],
  154. $parts['authority'],
  155. $parts['path'],
  156. $parts['query'],
  157. $parts['fragment']
  158. ));
  159. }
  160. /**
  161. * Create a new URI with a specific query string value removed.
  162. *
  163. * Any existing query string values that exactly match the provided key are
  164. * removed.
  165. *
  166. * Note: this function will convert "=" to "%3D" and "&" to "%26".
  167. *
  168. * @param UriInterface $uri URI to use as a base.
  169. * @param string $key Query string key value pair to remove.
  170. *
  171. * @return UriInterface
  172. */
  173. public static function withoutQueryValue(UriInterface $uri, $key)
  174. {
  175. $current = $uri->getQuery();
  176. if (!$current) {
  177. return $uri;
  178. }
  179. $result = [];
  180. foreach (explode('&', $current) as $part) {
  181. if (explode('=', $part)[0] !== $key) {
  182. $result[] = $part;
  183. };
  184. }
  185. return $uri->withQuery(implode('&', $result));
  186. }
  187. /**
  188. * Create a new URI with a specific query string value.
  189. *
  190. * Any existing query string values that exactly match the provided key are
  191. * removed and replaced with the given key value pair.
  192. *
  193. * Note: this function will convert "=" to "%3D" and "&" to "%26".
  194. *
  195. * @param UriInterface $uri URI to use as a base.
  196. * @param string $key Key to set.
  197. * @param string $value Value to set.
  198. *
  199. * @return UriInterface
  200. */
  201. public static function withQueryValue(UriInterface $uri, $key, $value)
  202. {
  203. $current = $uri->getQuery();
  204. $key = strtr($key, self::$replaceQuery);
  205. if (!$current) {
  206. $result = [];
  207. } else {
  208. $result = [];
  209. foreach (explode('&', $current) as $part) {
  210. if (explode('=', $part)[0] !== $key) {
  211. $result[] = $part;
  212. };
  213. }
  214. }
  215. if ($value !== null) {
  216. $result[] = $key . '=' . strtr($value, self::$replaceQuery);
  217. } else {
  218. $result[] = $key;
  219. }
  220. return $uri->withQuery(implode('&', $result));
  221. }
  222. /**
  223. * Create a URI from a hash of parse_url parts.
  224. *
  225. * @param array $parts
  226. *
  227. * @return self
  228. */
  229. public static function fromParts(array $parts)
  230. {
  231. $uri = new self();
  232. $uri->applyParts($parts);
  233. return $uri;
  234. }
  235. public function getScheme()
  236. {
  237. return $this->scheme;
  238. }
  239. public function getAuthority()
  240. {
  241. if (empty($this->host)) {
  242. return '';
  243. }
  244. $authority = $this->host;
  245. if (!empty($this->userInfo)) {
  246. $authority = $this->userInfo . '@' . $authority;
  247. }
  248. if ($this->isNonStandardPort($this->scheme, $this->host, $this->port)) {
  249. $authority .= ':' . $this->port;
  250. }
  251. return $authority;
  252. }
  253. public function getUserInfo()
  254. {
  255. return $this->userInfo;
  256. }
  257. public function getHost()
  258. {
  259. return $this->host;
  260. }
  261. public function getPort()
  262. {
  263. return $this->port;
  264. }
  265. public function getPath()
  266. {
  267. return $this->path == null ? '' : $this->path;
  268. }
  269. public function getQuery()
  270. {
  271. return $this->query;
  272. }
  273. public function getFragment()
  274. {
  275. return $this->fragment;
  276. }
  277. public function withScheme($scheme)
  278. {
  279. $scheme = $this->filterScheme($scheme);
  280. if ($this->scheme === $scheme) {
  281. return $this;
  282. }
  283. $new = clone $this;
  284. $new->scheme = $scheme;
  285. $new->port = $new->filterPort($new->scheme, $new->host, $new->port);
  286. return $new;
  287. }
  288. public function withUserInfo($user, $password = null)
  289. {
  290. $info = $user;
  291. if ($password) {
  292. $info .= ':' . $password;
  293. }
  294. if ($this->userInfo === $info) {
  295. return $this;
  296. }
  297. $new = clone $this;
  298. $new->userInfo = $info;
  299. return $new;
  300. }
  301. public function withHost($host)
  302. {
  303. if ($this->host === $host) {
  304. return $this;
  305. }
  306. $new = clone $this;
  307. $new->host = $host;
  308. return $new;
  309. }
  310. public function withPort($port)
  311. {
  312. $port = $this->filterPort($this->scheme, $this->host, $port);
  313. if ($this->port === $port) {
  314. return $this;
  315. }
  316. $new = clone $this;
  317. $new->port = $port;
  318. return $new;
  319. }
  320. public function withPath($path)
  321. {
  322. if (!is_string($path)) {
  323. throw new \InvalidArgumentException(
  324. 'Invalid path provided; must be a string'
  325. );
  326. }
  327. $path = $this->filterPath($path);
  328. if ($this->path === $path) {
  329. return $this;
  330. }
  331. $new = clone $this;
  332. $new->path = $path;
  333. return $new;
  334. }
  335. public function withQuery($query)
  336. {
  337. if (!is_string($query) && !method_exists($query, '__toString')) {
  338. throw new \InvalidArgumentException(
  339. 'Query string must be a string'
  340. );
  341. }
  342. $query = (string) $query;
  343. if (substr($query, 0, 1) === '?') {
  344. $query = substr($query, 1);
  345. }
  346. $query = $this->filterQueryAndFragment($query);
  347. if ($this->query === $query) {
  348. return $this;
  349. }
  350. $new = clone $this;
  351. $new->query = $query;
  352. return $new;
  353. }
  354. public function withFragment($fragment)
  355. {
  356. if (substr($fragment, 0, 1) === '#') {
  357. $fragment = substr($fragment, 1);
  358. }
  359. $fragment = $this->filterQueryAndFragment($fragment);
  360. if ($this->fragment === $fragment) {
  361. return $this;
  362. }
  363. $new = clone $this;
  364. $new->fragment = $fragment;
  365. return $new;
  366. }
  367. /**
  368. * Apply parse_url parts to a URI.
  369. *
  370. * @param $parts Array of parse_url parts to apply.
  371. */
  372. private function applyParts(array $parts)
  373. {
  374. $this->scheme = isset($parts['scheme'])
  375. ? $this->filterScheme($parts['scheme'])
  376. : '';
  377. $this->userInfo = isset($parts['user']) ? $parts['user'] : '';
  378. $this->host = isset($parts['host']) ? $parts['host'] : '';
  379. $this->port = !empty($parts['port'])
  380. ? $this->filterPort($this->scheme, $this->host, $parts['port'])
  381. : null;
  382. $this->path = isset($parts['path'])
  383. ? $this->filterPath($parts['path'])
  384. : '';
  385. $this->query = isset($parts['query'])
  386. ? $this->filterQueryAndFragment($parts['query'])
  387. : '';
  388. $this->fragment = isset($parts['fragment'])
  389. ? $this->filterQueryAndFragment($parts['fragment'])
  390. : '';
  391. if (isset($parts['pass'])) {
  392. $this->userInfo .= ':' . $parts['pass'];
  393. }
  394. }
  395. /**
  396. * Create a URI string from its various parts
  397. *
  398. * @param string $scheme
  399. * @param string $authority
  400. * @param string $path
  401. * @param string $query
  402. * @param string $fragment
  403. * @return string
  404. */
  405. private static function createUriString($scheme, $authority, $path, $query, $fragment)
  406. {
  407. $uri = '';
  408. if (!empty($scheme)) {
  409. $uri .= $scheme . '://';
  410. }
  411. if (!empty($authority)) {
  412. $uri .= $authority;
  413. }
  414. if ($path != null) {
  415. // Add a leading slash if necessary.
  416. if ($uri && substr($path, 0, 1) !== '/') {
  417. $uri .= '/';
  418. }
  419. $uri .= $path;
  420. }
  421. if ($query != null) {
  422. $uri .= '?' . $query;
  423. }
  424. if ($fragment != null) {
  425. $uri .= '#' . $fragment;
  426. }
  427. return $uri;
  428. }
  429. /**
  430. * Is a given port non-standard for the current scheme?
  431. *
  432. * @param string $scheme
  433. * @param string $host
  434. * @param int $port
  435. * @return bool
  436. */
  437. private static function isNonStandardPort($scheme, $host, $port)
  438. {
  439. if (!$scheme && $port) {
  440. return true;
  441. }
  442. if (!$host || !$port) {
  443. return false;
  444. }
  445. return !isset(static::$schemes[$scheme]) || $port !== static::$schemes[$scheme];
  446. }
  447. /**
  448. * @param string $scheme
  449. *
  450. * @return string
  451. */
  452. private function filterScheme($scheme)
  453. {
  454. $scheme = strtolower($scheme);
  455. $scheme = rtrim($scheme, ':/');
  456. return $scheme;
  457. }
  458. /**
  459. * @param string $scheme
  460. * @param string $host
  461. * @param int $port
  462. *
  463. * @return int|null
  464. *
  465. * @throws \InvalidArgumentException If the port is invalid.
  466. */
  467. private function filterPort($scheme, $host, $port)
  468. {
  469. if (null !== $port) {
  470. $port = (int) $port;
  471. if (1 > $port || 0xffff < $port) {
  472. throw new \InvalidArgumentException(
  473. sprintf('Invalid port: %d. Must be between 1 and 65535', $port)
  474. );
  475. }
  476. }
  477. return $this->isNonStandardPort($scheme, $host, $port) ? $port : null;
  478. }
  479. /**
  480. * Filters the path of a URI
  481. *
  482. * @param $path
  483. *
  484. * @return string
  485. */
  486. private function filterPath($path)
  487. {
  488. return preg_replace_callback(
  489. '/(?:[^' . self::$charUnreserved . self::$charSubDelims . ':@\/%]+|%(?![A-Fa-f0-9]{2}))/',
  490. [$this, 'rawurlencodeMatchZero'],
  491. $path
  492. );
  493. }
  494. /**
  495. * Filters the query string or fragment of a URI.
  496. *
  497. * @param $str
  498. *
  499. * @return string
  500. */
  501. private function filterQueryAndFragment($str)
  502. {
  503. return preg_replace_callback(
  504. '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/',
  505. [$this, 'rawurlencodeMatchZero'],
  506. $str
  507. );
  508. }
  509. private function rawurlencodeMatchZero(array $match)
  510. {
  511. return rawurlencode($match[0]);
  512. }
  513. }