PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/guzzlehttp/psr7/src/Uri.php

https://gitlab.com/ealexis.t/trends
PHP | 606 lines | 397 code | 88 blank | 121 comment | 66 complexity | 88cd732fda6c0c199eb459481af5d3c5 MD5 | raw file
  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(self::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. $hierPart = '';
  412. if (!empty($authority)) {
  413. if (!empty($scheme)) {
  414. $hierPart .= '//';
  415. }
  416. $hierPart .= $authority;
  417. }
  418. if ($path != null) {
  419. // Add a leading slash if necessary.
  420. if ($hierPart && substr($path, 0, 1) !== '/') {
  421. $hierPart .= '/';
  422. }
  423. $hierPart .= $path;
  424. }
  425. $uri .= $hierPart;
  426. if ($query != null) {
  427. $uri .= '?' . $query;
  428. }
  429. if ($fragment != null) {
  430. $uri .= '#' . $fragment;
  431. }
  432. return $uri;
  433. }
  434. /**
  435. * Is a given port non-standard for the current scheme?
  436. *
  437. * @param string $scheme
  438. * @param string $host
  439. * @param int $port
  440. * @return bool
  441. */
  442. private static function isNonStandardPort($scheme, $host, $port)
  443. {
  444. if (!$scheme && $port) {
  445. return true;
  446. }
  447. if (!$host || !$port) {
  448. return false;
  449. }
  450. return !isset(self::$schemes[$scheme]) || $port !== self::$schemes[$scheme];
  451. }
  452. /**
  453. * @param string $scheme
  454. *
  455. * @return string
  456. */
  457. private function filterScheme($scheme)
  458. {
  459. $scheme = strtolower($scheme);
  460. $scheme = rtrim($scheme, ':/');
  461. return $scheme;
  462. }
  463. /**
  464. * @param string $scheme
  465. * @param string $host
  466. * @param int $port
  467. *
  468. * @return int|null
  469. *
  470. * @throws \InvalidArgumentException If the port is invalid.
  471. */
  472. private function filterPort($scheme, $host, $port)
  473. {
  474. if (null !== $port) {
  475. $port = (int) $port;
  476. if (1 > $port || 0xffff < $port) {
  477. throw new \InvalidArgumentException(
  478. sprintf('Invalid port: %d. Must be between 1 and 65535', $port)
  479. );
  480. }
  481. }
  482. return $this->isNonStandardPort($scheme, $host, $port) ? $port : null;
  483. }
  484. /**
  485. * Filters the path of a URI
  486. *
  487. * @param $path
  488. *
  489. * @return string
  490. */
  491. private function filterPath($path)
  492. {
  493. return preg_replace_callback(
  494. '/(?:[^' . self::$charUnreserved . self::$charSubDelims . ':@\/%]+|%(?![A-Fa-f0-9]{2}))/',
  495. [$this, 'rawurlencodeMatchZero'],
  496. $path
  497. );
  498. }
  499. /**
  500. * Filters the query string or fragment of a URI.
  501. *
  502. * @param $str
  503. *
  504. * @return string
  505. */
  506. private function filterQueryAndFragment($str)
  507. {
  508. return preg_replace_callback(
  509. '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/',
  510. [$this, 'rawurlencodeMatchZero'],
  511. $str
  512. );
  513. }
  514. private function rawurlencodeMatchZero(array $match)
  515. {
  516. return rawurlencode($match[0]);
  517. }
  518. }