Http.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. /**
  3. * League.Uri (https://uri.thephpleague.com)
  4. *
  5. * (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace League\Uri;
  12. use Deprecated;
  13. use JsonSerializable;
  14. use League\Uri\Contracts\Conditionable;
  15. use League\Uri\Contracts\Transformable;
  16. use League\Uri\Contracts\UriException;
  17. use League\Uri\Contracts\UriInterface;
  18. use League\Uri\Exceptions\SyntaxError;
  19. use League\Uri\UriTemplate\TemplateCanNotBeExpanded;
  20. use Psr\Http\Message\UriInterface as Psr7UriInterface;
  21. use Stringable;
  22. use Uri\Rfc3986\Uri as Rfc3986Uri;
  23. use Uri\WhatWg\Url as WhatWgUrl;
  24. use function is_bool;
  25. use function ltrim;
  26. /**
  27. * @phpstan-import-type InputComponentMap from UriString
  28. */
  29. final class Http implements Stringable, Psr7UriInterface, JsonSerializable, Conditionable, Transformable
  30. {
  31. private readonly UriInterface $uri;
  32. private function __construct(UriInterface $uri)
  33. {
  34. if (null === $uri->getScheme() && '' === $uri->getHost()) {
  35. throw new SyntaxError('An URI without scheme cannot contain an empty host string according to PSR-7: '.$uri);
  36. }
  37. $port = $uri->getPort();
  38. if (null !== $port && ($port < 0 || $port > 65535)) {
  39. throw new SyntaxError('The URI port is outside the established TCP and UDP port ranges: '.$uri);
  40. }
  41. $this->uri = $this->normalizePsr7Uri($uri);
  42. }
  43. /**
  44. * PSR-7 UriInterface makes the following normalization.
  45. *
  46. * Safely stringify input when possible for League UriInterface compatibility.
  47. *
  48. * Query, Fragment and User Info when undefined are normalized to the empty string
  49. */
  50. private function normalizePsr7Uri(UriInterface $uri): UriInterface
  51. {
  52. $components = [];
  53. if ('' === $uri->getFragment()) {
  54. $components['fragment'] = null;
  55. }
  56. if ('' === $uri->getQuery()) {
  57. $components['query'] = null;
  58. }
  59. if ('' === $uri->getUserInfo()) {
  60. $components['user'] = null;
  61. $components['pass'] = null;
  62. }
  63. return match ($components) {
  64. [] => $uri,
  65. default => Uri::fromComponents([...$uri->toComponents(), ...$components]),
  66. };
  67. }
  68. /**
  69. * Create a new instance from a string or a stringable object.
  70. */
  71. public static function new(Rfc3986Uri|WhatwgUrl|Stringable|string $uri = ''): self
  72. {
  73. return new self(Uri::new($uri));
  74. }
  75. /**
  76. * Create a new instance from a string or a stringable structure or returns null on failure.
  77. */
  78. public static function tryNew(Rfc3986Uri|WhatwgUrl|Stringable|string $uri = ''): ?self
  79. {
  80. try {
  81. return self::new($uri);
  82. } catch (UriException) {
  83. return null;
  84. }
  85. }
  86. /**
  87. * Create a new instance from a hash of parse_url parts.
  88. *
  89. * @param InputComponentMap $components a hash representation of the URI similar
  90. * to PHP parse_url function result
  91. */
  92. public static function fromComponents(array $components): self
  93. {
  94. $components += [
  95. 'scheme' => null, 'user' => null, 'pass' => null, 'host' => null,
  96. 'port' => null, 'path' => '', 'query' => null, 'fragment' => null,
  97. ];
  98. if ('' === $components['user']) {
  99. $components['user'] = null;
  100. }
  101. if ('' === $components['pass']) {
  102. $components['pass'] = null;
  103. }
  104. if ('' === $components['query']) {
  105. $components['query'] = null;
  106. }
  107. if ('' === $components['fragment']) {
  108. $components['fragment'] = null;
  109. }
  110. return new self(Uri::fromComponents($components));
  111. }
  112. /**
  113. * Create a new instance from the environment.
  114. */
  115. public static function fromServer(array $server): self
  116. {
  117. return new self(Uri::fromServer($server));
  118. }
  119. /**
  120. * Creates a new instance from a template.
  121. *
  122. * @throws TemplateCanNotBeExpanded if the variables are invalid or missing
  123. * @throws UriException if the variables are invalid or missing
  124. */
  125. public static function fromTemplate(Stringable|string $template, iterable $variables = []): self
  126. {
  127. return new self(Uri::fromTemplate($template, $variables));
  128. }
  129. /**
  130. * Returns a new instance from a URI and a Base URI.or null on failure.
  131. *
  132. * The returned URI must be absolute if a base URI is provided
  133. */
  134. public static function parse(WhatWgUrl|Rfc3986Uri|Stringable|string $uri, WhatWgUrl|Rfc3986Uri|Stringable|string|null $baseUri = null): ?self
  135. {
  136. return null !== ($uri = Uri::parse($uri, $baseUri)) ? new self($uri) : null;
  137. }
  138. public function getScheme(): string
  139. {
  140. return $this->uri->getScheme() ?? '';
  141. }
  142. public function getAuthority(): string
  143. {
  144. return $this->uri->getAuthority() ?? '';
  145. }
  146. public function getUserInfo(): string
  147. {
  148. return $this->uri->getUserInfo() ?? '';
  149. }
  150. public function getHost(): string
  151. {
  152. return $this->uri->getHost() ?? '';
  153. }
  154. public function getPort(): ?int
  155. {
  156. return $this->uri->getPort();
  157. }
  158. public function getPath(): string
  159. {
  160. $path = $this->uri->getPath();
  161. return match (true) {
  162. str_starts_with($path, '//') => '/'.ltrim($path, '/'),
  163. default => $path,
  164. };
  165. }
  166. public function getQuery(): string
  167. {
  168. return $this->uri->getQuery() ?? '';
  169. }
  170. public function getFragment(): string
  171. {
  172. return $this->uri->getFragment() ?? '';
  173. }
  174. public function __toString(): string
  175. {
  176. return $this->uri->toString();
  177. }
  178. public function jsonSerialize(): string
  179. {
  180. return $this->uri->toString();
  181. }
  182. /**
  183. * Safely stringify input when possible for League UriInterface compatibility.
  184. */
  185. private function filterInput(string $str): ?string
  186. {
  187. return match ('') {
  188. $str => null,
  189. default => $str,
  190. };
  191. }
  192. private function newInstance(UriInterface $uri): self
  193. {
  194. return match ($this->uri->toString()) {
  195. $uri->toString() => $this,
  196. default => new self($uri),
  197. };
  198. }
  199. public function when(callable|bool $condition, callable $onSuccess, ?callable $onFail = null): static
  200. {
  201. if (!is_bool($condition)) {
  202. $condition = $condition($this);
  203. }
  204. return match (true) {
  205. $condition => $onSuccess($this),
  206. null !== $onFail => $onFail($this),
  207. default => $this,
  208. } ?? $this;
  209. }
  210. public function transform(callable $callback): static
  211. {
  212. return $callback($this);
  213. }
  214. public function withScheme(string $scheme): self
  215. {
  216. return $this->newInstance($this->uri->withScheme($this->filterInput($scheme)));
  217. }
  218. public function withUserInfo(string $user, ?string $password = null): self
  219. {
  220. return $this->newInstance($this->uri->withUserInfo($this->filterInput($user), $password));
  221. }
  222. public function withHost(string $host): self
  223. {
  224. return $this->newInstance($this->uri->withHost($this->filterInput($host)));
  225. }
  226. public function withPort(?int $port): self
  227. {
  228. return $this->newInstance($this->uri->withPort($port));
  229. }
  230. public function withPath(string $path): self
  231. {
  232. return $this->newInstance($this->uri->withPath($path));
  233. }
  234. public function withQuery(string $query): self
  235. {
  236. return $this->newInstance($this->uri->withQuery($this->filterInput($query)));
  237. }
  238. public function withFragment(string $fragment): self
  239. {
  240. return $this->newInstance($this->uri->withFragment($this->filterInput($fragment)));
  241. }
  242. /**
  243. * DEPRECATION WARNING! This method will be removed in the next major point release.
  244. *
  245. * @deprecated Since version 7.6.0
  246. * @codeCoverageIgnore
  247. * @see Http::parse()
  248. *
  249. * Create a new instance from a URI and a Base URI.
  250. *
  251. * The returned URI must be absolute.
  252. */
  253. #[Deprecated(message:'use League\Uri\Http::parse() instead', since:'league/uri:7.6.0')]
  254. public static function fromBaseUri(Rfc3986Uri|WhatwgUrl|Stringable|string $uri, Rfc3986Uri|WhatwgUrl|Stringable|string|null $baseUri = null): self
  255. {
  256. return new self(Uri::fromBaseUri($uri, $baseUri));
  257. }
  258. /**
  259. * DEPRECATION WARNING! This method will be removed in the next major point release.
  260. *
  261. * @deprecated Since version 7.0.0
  262. * @codeCoverageIgnore
  263. * @see Http::new()
  264. *
  265. * Create a new instance from a string.
  266. */
  267. #[Deprecated(message:'use League\Uri\Http::new() instead', since:'league/uri:7.0.0')]
  268. public static function createFromString(Stringable|string $uri = ''): self
  269. {
  270. return self::new($uri);
  271. }
  272. /**
  273. * DEPRECATION WARNING! This method will be removed in the next major point release.
  274. *
  275. * @deprecated Since version 7.0.0
  276. * @codeCoverageIgnore
  277. * @see Http::fromComponents()
  278. *
  279. * Create a new instance from a hash of parse_url parts.
  280. *
  281. * @param InputComponentMap $components a hash representation of the URI similar
  282. * to PHP parse_url function result
  283. */
  284. #[Deprecated(message:'use League\Uri\Http::fromComponents() instead', since:'league/uri:7.0.0')]
  285. public static function createFromComponents(array $components): self
  286. {
  287. return self::fromComponents($components);
  288. }
  289. /**
  290. * DEPRECATION WARNING! This method will be removed in the next major point release.
  291. *
  292. * @deprecated Since version 7.0.0
  293. * @codeCoverageIgnore
  294. * @see Http::fromServer()
  295. *
  296. * Create a new instance from the environment.
  297. */
  298. #[Deprecated(message:'use League\Uri\Http::fromServer() instead', since:'league/uri:7.0.0')]
  299. public static function createFromServer(array $server): self
  300. {
  301. return self::fromServer($server);
  302. }
  303. /**
  304. * DEPRECATION WARNING! This method will be removed in the next major point release.
  305. *
  306. * @deprecated Since version 7.0.0
  307. * @codeCoverageIgnore
  308. * @see Http::new()
  309. *
  310. * Create a new instance from a URI object.
  311. */
  312. #[Deprecated(message:'use League\Uri\Http::new() instead', since:'league/uri:7.0.0')]
  313. public static function createFromUri(Psr7UriInterface|UriInterface $uri): self
  314. {
  315. return self::new($uri);
  316. }
  317. /**
  318. * DEPRECATION WARNING! This method will be removed in the next major point release.
  319. *
  320. * @deprecated Since version 7.0.0
  321. * @codeCoverageIgnore
  322. * @see Http::fromBaseUri()
  323. *
  324. * Create a new instance from a URI and a Base URI.
  325. *
  326. * The returned URI must be absolute.
  327. */
  328. #[Deprecated(message:'use League\Uri\Http::fromBaseUri() instead', since:'league/uri:7.0.0')]
  329. public static function createFromBaseUri(Stringable|string $uri, Stringable|string|null $baseUri = null): self
  330. {
  331. return self::fromBaseUri($uri, $baseUri);
  332. }
  333. }