Debian Codegraph @

lib/3rdParty/composer/nyholm/psr7/src/RequestTrait.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Nyholm\Psr7;
6
7 use Psr\Http\Message\RequestInterface;
8 use Psr\Http\Message\UriInterface;
9
10 /**
11 * @author Michael Dowling and contributors to guzzlehttp/psr7
12 * @author Tobias Nyholm <[email protected]>
13 * @author Martijn van der Ven <[email protected]>
14 *
15 * @internal should not be used outside of Nyholm/Psr7 as it does not fall under our BC promise
16 */
17 trait RequestTrait
18 {
19 /** @var string */
20 private $method;
21
22 /** @var string|null */
23 private $requestTarget;
24
25 /** @var UriInterface|null */
26 private $uri;
27
28 public function getRequestTarget(): string
29 {
30 if (null !== $this->requestTarget) {
31 return $this->requestTarget;
32 }
33
34 if ('' === $target = $this->uri->getPath()) {
35 $target = '/';
36 }
37 if ('' !== $this->uri->getQuery()) {
38 $target .= '?' . $this->uri->getQuery();
39 }
40
41 return $target;
42 }
43
44 /**
45 * @return static
46 */
47 public function withRequestTarget($requestTarget): RequestInterface
48 {
49 if (!\is_string($requestTarget)) {
50 throw new \InvalidArgumentException('Request target must be a string');
51 }
52
53 if (\preg_match('#\s#', $requestTarget)) {
54 throw new \InvalidArgumentException('Invalid request target provided; cannot contain whitespace');
55 }
56
57 $new = clone $this;
58 $new->requestTarget = $requestTarget;
59
60 return $new;
61 }
62
63 public function getMethod(): string
64 {
65 return $this->method;
66 }
67
68 /**
69 * @return static
70 */
71 public function withMethod($method): RequestInterface
72 {
73 if (!\is_string($method)) {
74 throw new \InvalidArgumentException('Method must be a string');
75 }
76
77 $new = clone $this;
78 $new->method = $method;
79
80 return $new;
81 }
82
83 public function getUri(): UriInterface
84 {
85 return $this->uri;
86 }
87
88 /**
89 * @return static
90 */
91 public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface
92 {
93 if ($uri === $this->uri) {
94 return $this;
95 }
96
97 $new = clone $this;
98 $new->uri = $uri;
99
100 if (!$preserveHost || !$this->hasHeader('Host')) {
101 $new->updateHostFromUri();
102 }
103
104 return $new;
105 }
106
107 private function updateHostFromUri(): void
108 {
109 if ('' === $host = $this->uri->getHost()) {
110 return;
111 }
112
113 if (null !== ($port = $this->uri->getPort())) {
114 $host .= ':' . $port;
115 }
116
117 if (isset($this->headerNames['host'])) {
118 $header = $this->headerNames['host'];
119 } else {
120 $this->headerNames['host'] = $header = 'Host';
121 }
122
123 // Ensure Host is the first header.
124 // See: http://tools.ietf.org/html/rfc7230#section-5.4
125 $this->headers = [$header => [$host]] + $this->headers;
126 }
127 }