Uri.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. <?php
  2. namespace GuzzleHttp\Psr7;
  3. use Psr\Http\Message\UriInterface;
  4. /**
  5. * PSR-7 URI implementation.
  6. *
  7. * @author Michael Dowling
  8. * @author Tobias Schultze
  9. * @author Matthew Weier O'Phinney
  10. */
  11. class Uri implements UriInterface
  12. {
  13. /**
  14. * Absolute http and https URIs require a host per RFC 7230 Section 2.7
  15. * but in generic URIs the host can be empty. So for http(s) URIs
  16. * we apply this default host when no host is given yet to form a
  17. * valid URI.
  18. */
  19. const HTTP_DEFAULT_HOST = 'localhost';
  20. private static $defaultPorts = [
  21. 'http' => 80,
  22. 'https' => 443,
  23. 'ftp' => 21,
  24. 'gopher' => 70,
  25. 'nntp' => 119,
  26. 'news' => 119,
  27. 'telnet' => 23,
  28. 'tn3270' => 23,
  29. 'imap' => 143,
  30. 'pop' => 110,
  31. 'ldap' => 389,
  32. ];
  33. private static $charUnreserved = 'a-zA-Z0-9_\-\.~';
  34. private static $charSubDelims = '!\$&\'\(\)\*\+,;=';
  35. private static $replaceQuery = ['=' => '%3D', '&' => '%26'];
  36. /** @var string Uri scheme. */
  37. private $scheme = '';
  38. /** @var string Uri user info. */
  39. private $userInfo = '';
  40. /** @var string Uri host. */
  41. private $host = '';
  42. /** @var int|null Uri port. */
  43. private $port;
  44. /** @var string Uri path. */
  45. private $path = '';
  46. /** @var string Uri query string. */
  47. private $query = '';
  48. /** @var string Uri fragment. */
  49. private $fragment = '';
  50. /**
  51. * @param string $uri URI to parse
  52. */
  53. public function __construct($uri = '')
  54. {
  55. // weak type check to also accept null until we can add scalar type hints
  56. if ($uri != '') {
  57. $parts = parse_url($uri);
  58. if ($parts === false) {
  59. throw new \InvalidArgumentException("Unable to parse URI: $uri");
  60. }
  61. $this->applyParts($parts);
  62. }
  63. }
  64. public function __toString()
  65. {
  66. return self::composeComponents(
  67. $this->scheme,
  68. $this->getAuthority(),
  69. $this->path,
  70. $this->query,
  71. $this->fragment
  72. );
  73. }
  74. /**
  75. * Composes a URI reference string from its various components.
  76. *
  77. * Usually this method does not need to be called manually but instead is used indirectly via
  78. * `Psr\Http\Message\UriInterface::__toString`.
  79. *
  80. * PSR-7 UriInterface treats an empty component the same as a missing component as
  81. * getQuery(), getFragment() etc. always return a string. This explains the slight
  82. * difference to RFC 3986 Section 5.3.
  83. *
  84. * Another adjustment is that the authority separator is added even when the authority is missing/empty
  85. * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with
  86. * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But
  87. * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
  88. * that format).
  89. *
  90. * @param string $scheme
  91. * @param string $authority
  92. * @param string $path
  93. * @param string $query
  94. * @param string $fragment
  95. *
  96. * @return string
  97. *
  98. * @link https://tools.ietf.org/html/rfc3986#section-5.3
  99. */
  100. public static function composeComponents($scheme, $authority, $path, $query, $fragment)
  101. {
  102. $uri = '';
  103. // weak type checks to also accept null until we can add scalar type hints
  104. if ($scheme != '') {
  105. $uri .= $scheme . ':';
  106. }
  107. if ($authority != ''|| $scheme === 'file') {
  108. $uri .= '//' . $authority;
  109. }
  110. $uri .= $path;
  111. if ($query != '') {
  112. $uri .= '?' . $query;
  113. }
  114. if ($fragment != '') {
  115. $uri .= '#' . $fragment;
  116. }
  117. return $uri;
  118. }
  119. /**
  120. * Whether the URI has the default port of the current scheme.
  121. *
  122. * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used
  123. * independently of the implementation.
  124. *
  125. * @param UriInterface $uri
  126. *
  127. * @return bool
  128. */
  129. public static function isDefaultPort(UriInterface $uri)
  130. {
  131. return $uri->getPort() === null
  132. || (isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]);
  133. }
  134. /**
  135. * Whether the URI is absolute, i.e. it has a scheme.
  136. *
  137. * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
  138. * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
  139. * to another URI, the base URI. Relative references can be divided into several forms:
  140. * - network-path references, e.g. '//example.com/path'
  141. * - absolute-path references, e.g. '/path'
  142. * - relative-path references, e.g. 'subpath'
  143. *
  144. * @param UriInterface $uri
  145. *
  146. * @return bool
  147. * @see Uri::isNetworkPathReference
  148. * @see Uri::isAbsolutePathReference
  149. * @see Uri::isRelativePathReference
  150. * @link https://tools.ietf.org/html/rfc3986#section-4
  151. */
  152. public static function isAbsolute(UriInterface $uri)
  153. {
  154. return $uri->getScheme() !== '';
  155. }
  156. /**
  157. * Whether the URI is a network-path reference.
  158. *
  159. * A relative reference that begins with two slash characters is termed an network-path reference.
  160. *
  161. * @param UriInterface $uri
  162. *
  163. * @return bool
  164. * @link https://tools.ietf.org/html/rfc3986#section-4.2
  165. */
  166. public static function isNetworkPathReference(UriInterface $uri)
  167. {
  168. return $uri->getScheme() === '' && $uri->getAuthority() !== '';
  169. }
  170. /**
  171. * Whether the URI is a absolute-path reference.
  172. *
  173. * A relative reference that begins with a single slash character is termed an absolute-path reference.
  174. *
  175. * @param UriInterface $uri
  176. *
  177. * @return bool
  178. * @link https://tools.ietf.org/html/rfc3986#section-4.2
  179. */
  180. public static function isAbsolutePathReference(UriInterface $uri)
  181. {
  182. return $uri->getScheme() === ''
  183. && $uri->getAuthority() === ''
  184. && isset($uri->getPath()[0])
  185. && $uri->getPath()[0] === '/';
  186. }
  187. /**
  188. * Whether the URI is a relative-path reference.
  189. *
  190. * A relative reference that does not begin with a slash character is termed a relative-path reference.
  191. *
  192. * @param UriInterface $uri
  193. *
  194. * @return bool
  195. * @link https://tools.ietf.org/html/rfc3986#section-4.2
  196. */
  197. public static function isRelativePathReference(UriInterface $uri)
  198. {
  199. return $uri->getScheme() === ''
  200. && $uri->getAuthority() === ''
  201. && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/');
  202. }
  203. /**
  204. * Whether the URI is a same-document reference.
  205. *
  206. * A same-document reference refers to a URI that is, aside from its fragment
  207. * component, identical to the base URI. When no base URI is given, only an empty
  208. * URI reference (apart from its fragment) is considered a same-document reference.
  209. *
  210. * @param UriInterface $uri The URI to check
  211. * @param UriInterface|null $base An optional base URI to compare against
  212. *
  213. * @return bool
  214. * @link https://tools.ietf.org/html/rfc3986#section-4.4
  215. */
  216. public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null)
  217. {
  218. if ($base !== null) {
  219. $uri = UriResolver::resolve($base, $uri);
  220. return ($uri->getScheme() === $base->getScheme())
  221. && ($uri->getAuthority() === $base->getAuthority())
  222. && ($uri->getPath() === $base->getPath())
  223. && ($uri->getQuery() === $base->getQuery());
  224. }
  225. return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === '';
  226. }
  227. /**
  228. * Removes dot segments from a path and returns the new path.
  229. *
  230. * @param string $path
  231. *
  232. * @return string
  233. *
  234. * @deprecated since version 1.4. Use UriResolver::removeDotSegments instead.
  235. * @see UriResolver::removeDotSegments
  236. */
  237. public static function removeDotSegments($path)
  238. {
  239. return UriResolver::removeDotSegments($path);
  240. }
  241. /**
  242. * Converts the relative URI into a new URI that is resolved against the base URI.
  243. *
  244. * @param UriInterface $base Base URI
  245. * @param string|UriInterface $rel Relative URI
  246. *
  247. * @return UriInterface
  248. *
  249. * @deprecated since version 1.4. Use UriResolver::resolve instead.
  250. * @see UriResolver::resolve
  251. */
  252. public static function resolve(UriInterface $base, $rel)
  253. {
  254. if (!($rel instanceof UriInterface)) {
  255. $rel = new self($rel);
  256. }
  257. return UriResolver::resolve($base, $rel);
  258. }
  259. /**
  260. * Creates a new URI with a specific query string value removed.
  261. *
  262. * Any existing query string values that exactly match the provided key are
  263. * removed.
  264. *
  265. * @param UriInterface $uri URI to use as a base.
  266. * @param string $key Query string key to remove.
  267. *
  268. * @return UriInterface
  269. */
  270. public static function withoutQueryValue(UriInterface $uri, $key)
  271. {
  272. $current = $uri->getQuery();
  273. if ($current === '') {
  274. return $uri;
  275. }
  276. $decodedKey = rawurldecode($key);
  277. $result = array_filter(explode('&', $current), function ($part) use ($decodedKey) {
  278. return rawurldecode(explode('=', $part)[0]) !== $decodedKey;
  279. });
  280. return $uri->withQuery(implode('&', $result));
  281. }
  282. /**
  283. * Creates a new URI with a specific query string value.
  284. *
  285. * Any existing query string values that exactly match the provided key are
  286. * removed and replaced with the given key value pair.
  287. *
  288. * A value of null will set the query string key without a value, e.g. "key"
  289. * instead of "key=value".
  290. *
  291. * @param UriInterface $uri URI to use as a base.
  292. * @param string $key Key to set.
  293. * @param string|null $value Value to set
  294. *
  295. * @return UriInterface
  296. */
  297. public static function withQueryValue(UriInterface $uri, $key, $value)
  298. {
  299. $current = $uri->getQuery();
  300. if ($current === '') {
  301. $result = [];
  302. } else {
  303. $decodedKey = rawurldecode($key);
  304. $result = array_filter(explode('&', $current), function ($part) use ($decodedKey) {
  305. return rawurldecode(explode('=', $part)[0]) !== $decodedKey;
  306. });
  307. }
  308. // Query string separators ("=", "&") within the key or value need to be encoded
  309. // (while preventing double-encoding) before setting the query string. All other
  310. // chars that need percent-encoding will be encoded by withQuery().
  311. $key = strtr($key, self::$replaceQuery);
  312. if ($value !== null) {
  313. $result[] = $key . '=' . strtr($value, self::$replaceQuery);
  314. } else {
  315. $result[] = $key;
  316. }
  317. return $uri->withQuery(implode('&', $result));
  318. }
  319. /**
  320. * Creates a URI from a hash of `parse_url` components.
  321. *
  322. * @param array $parts
  323. *
  324. * @return UriInterface
  325. * @link http://php.net/manual/en/function.parse-url.php
  326. *
  327. * @throws \InvalidArgumentException If the components do not form a valid URI.
  328. */
  329. public static function fromParts(array $parts)
  330. {
  331. $uri = new self();
  332. $uri->applyParts($parts);
  333. $uri->validateState();
  334. return $uri;
  335. }
  336. public function getScheme()
  337. {
  338. return $this->scheme;
  339. }
  340. public function getAuthority()
  341. {
  342. $authority = $this->host;
  343. if ($this->userInfo !== '') {
  344. $authority = $this->userInfo . '@' . $authority;
  345. }
  346. if ($this->port !== null) {
  347. $authority .= ':' . $this->port;
  348. }
  349. return $authority;
  350. }
  351. public function getUserInfo()
  352. {
  353. return $this->userInfo;
  354. }
  355. public function getHost()
  356. {
  357. return $this->host;
  358. }
  359. public function getPort()
  360. {
  361. return $this->port;
  362. }
  363. public function getPath()
  364. {
  365. return $this->path;
  366. }
  367. public function getQuery()
  368. {
  369. return $this->query;
  370. }
  371. public function getFragment()
  372. {
  373. return $this->fragment;
  374. }
  375. public function withScheme($scheme)
  376. {
  377. $scheme = $this->filterScheme($scheme);
  378. if ($this->scheme === $scheme) {
  379. return $this;
  380. }
  381. $new = clone $this;
  382. $new->scheme = $scheme;
  383. $new->removeDefaultPort();
  384. $new->validateState();
  385. return $new;
  386. }
  387. public function withUserInfo($user, $password = null)
  388. {
  389. $info = $user;
  390. if ($password != '') {
  391. $info .= ':' . $password;
  392. }
  393. if ($this->userInfo === $info) {
  394. return $this;
  395. }
  396. $new = clone $this;
  397. $new->userInfo = $info;
  398. $new->validateState();
  399. return $new;
  400. }
  401. public function withHost($host)
  402. {
  403. $host = $this->filterHost($host);
  404. if ($this->host === $host) {
  405. return $this;
  406. }
  407. $new = clone $this;
  408. $new->host = $host;
  409. $new->validateState();
  410. return $new;
  411. }
  412. public function withPort($port)
  413. {
  414. $port = $this->filterPort($port);
  415. if ($this->port === $port) {
  416. return $this;
  417. }
  418. $new = clone $this;
  419. $new->port = $port;
  420. $new->removeDefaultPort();
  421. $new->validateState();
  422. return $new;
  423. }
  424. public function withPath($path)
  425. {
  426. $path = $this->filterPath($path);
  427. if ($this->path === $path) {
  428. return $this;
  429. }
  430. $new = clone $this;
  431. $new->path = $path;
  432. $new->validateState();
  433. return $new;
  434. }
  435. public function withQuery($query)
  436. {
  437. $query = $this->filterQueryAndFragment($query);
  438. if ($this->query === $query) {
  439. return $this;
  440. }
  441. $new = clone $this;
  442. $new->query = $query;
  443. return $new;
  444. }
  445. public function withFragment($fragment)
  446. {
  447. $fragment = $this->filterQueryAndFragment($fragment);
  448. if ($this->fragment === $fragment) {
  449. return $this;
  450. }
  451. $new = clone $this;
  452. $new->fragment = $fragment;
  453. return $new;
  454. }
  455. /**
  456. * Apply parse_url parts to a URI.
  457. *
  458. * @param array $parts Array of parse_url parts to apply.
  459. */
  460. private function applyParts(array $parts)
  461. {
  462. $this->scheme = isset($parts['scheme'])
  463. ? $this->filterScheme($parts['scheme'])
  464. : '';
  465. $this->userInfo = isset($parts['user']) ? $parts['user'] : '';
  466. $this->host = isset($parts['host'])
  467. ? $this->filterHost($parts['host'])
  468. : '';
  469. $this->port = isset($parts['port'])
  470. ? $this->filterPort($parts['port'])
  471. : null;
  472. $this->path = isset($parts['path'])
  473. ? $this->filterPath($parts['path'])
  474. : '';
  475. $this->query = isset($parts['query'])
  476. ? $this->filterQueryAndFragment($parts['query'])
  477. : '';
  478. $this->fragment = isset($parts['fragment'])
  479. ? $this->filterQueryAndFragment($parts['fragment'])
  480. : '';
  481. if (isset($parts['pass'])) {
  482. $this->userInfo .= ':' . $parts['pass'];
  483. }
  484. $this->removeDefaultPort();
  485. }
  486. /**
  487. * @param string $scheme
  488. *
  489. * @return string
  490. *
  491. * @throws \InvalidArgumentException If the scheme is invalid.
  492. */
  493. private function filterScheme($scheme)
  494. {
  495. if (!is_string($scheme)) {
  496. throw new \InvalidArgumentException('Scheme must be a string');
  497. }
  498. return strtolower($scheme);
  499. }
  500. /**
  501. * @param string $host
  502. *
  503. * @return string
  504. *
  505. * @throws \InvalidArgumentException If the host is invalid.
  506. */
  507. private function filterHost($host)
  508. {
  509. if (!is_string($host)) {
  510. throw new \InvalidArgumentException('Host must be a string');
  511. }
  512. return strtolower($host);
  513. }
  514. /**
  515. * @param int|null $port
  516. *
  517. * @return int|null
  518. *
  519. * @throws \InvalidArgumentException If the port is invalid.
  520. */
  521. private function filterPort($port)
  522. {
  523. if ($port === null) {
  524. return null;
  525. }
  526. $port = (int) $port;
  527. if (1 > $port || 0xffff < $port) {
  528. throw new \InvalidArgumentException(
  529. sprintf('Invalid port: %d. Must be between 1 and 65535', $port)
  530. );
  531. }
  532. return $port;
  533. }
  534. private function removeDefaultPort()
  535. {
  536. if ($this->port !== null && self::isDefaultPort($this)) {
  537. $this->port = null;
  538. }
  539. }
  540. /**
  541. * Filters the path of a URI
  542. *
  543. * @param string $path
  544. *
  545. * @return string
  546. *
  547. * @throws \InvalidArgumentException If the path is invalid.
  548. */
  549. private function filterPath($path)
  550. {
  551. if (!is_string($path)) {
  552. throw new \InvalidArgumentException('Path must be a string');
  553. }
  554. return preg_replace_callback(
  555. '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
  556. [$this, 'rawurlencodeMatchZero'],
  557. $path
  558. );
  559. }
  560. /**
  561. * Filters the query string or fragment of a URI.
  562. *
  563. * @param string $str
  564. *
  565. * @return string
  566. *
  567. * @throws \InvalidArgumentException If the query or fragment is invalid.
  568. */
  569. private function filterQueryAndFragment($str)
  570. {
  571. if (!is_string($str)) {
  572. throw new \InvalidArgumentException('Query and fragment must be a string');
  573. }
  574. return preg_replace_callback(
  575. '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
  576. [$this, 'rawurlencodeMatchZero'],
  577. $str
  578. );
  579. }
  580. private function rawurlencodeMatchZero(array $match)
  581. {
  582. return rawurlencode($match[0]);
  583. }
  584. private function validateState()
  585. {
  586. if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) {
  587. $this->host = self::HTTP_DEFAULT_HOST;
  588. }
  589. if ($this->getAuthority() === '') {
  590. if (0 === strpos($this->path, '//')) {
  591. throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"');
  592. }
  593. if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) {
  594. throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon');
  595. }
  596. } elseif (isset($this->path[0]) && $this->path[0] !== '/') {
  597. @trigger_error(
  598. 'The path of a URI with an authority must start with a slash "/" or be empty. Automagically fixing the URI ' .
  599. 'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.',
  600. E_USER_DEPRECATED
  601. );
  602. $this->path = '/'. $this->path;
  603. //throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty');
  604. }
  605. }
  606. }