Utils.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\RequestInterface;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Psr\Http\Message\StreamInterface;
  7. use Psr\Http\Message\UriInterface;
  8. final class Utils
  9. {
  10. /**
  11. * Remove the items given by the keys, case insensitively from the data.
  12. *
  13. * @param string[] $keys
  14. */
  15. public static function caselessRemove(array $keys, array $data): array
  16. {
  17. $result = [];
  18. foreach ($keys as &$key) {
  19. $key = strtolower($key);
  20. }
  21. foreach ($data as $k => $v) {
  22. if (!is_string($k) || !in_array(strtolower($k), $keys)) {
  23. $result[$k] = $v;
  24. }
  25. }
  26. return $result;
  27. }
  28. /**
  29. * Copy the contents of a stream into another stream until the given number
  30. * of bytes have been read.
  31. *
  32. * @param StreamInterface $source Stream to read from
  33. * @param StreamInterface $dest Stream to write to
  34. * @param int $maxLen Maximum number of bytes to read. Pass -1
  35. * to read the entire stream.
  36. *
  37. * @throws \RuntimeException on error.
  38. */
  39. public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void
  40. {
  41. $bufferSize = 8192;
  42. if ($maxLen === -1) {
  43. while (!$source->eof()) {
  44. if (!$dest->write($source->read($bufferSize))) {
  45. break;
  46. }
  47. }
  48. } else {
  49. $remaining = $maxLen;
  50. while ($remaining > 0 && !$source->eof()) {
  51. $buf = $source->read(min($bufferSize, $remaining));
  52. $len = strlen($buf);
  53. if (!$len) {
  54. break;
  55. }
  56. $remaining -= $len;
  57. $dest->write($buf);
  58. }
  59. }
  60. }
  61. /**
  62. * Copy the contents of a stream into a string until the given number of
  63. * bytes have been read.
  64. *
  65. * @param StreamInterface $stream Stream to read
  66. * @param int $maxLen Maximum number of bytes to read. Pass -1
  67. * to read the entire stream.
  68. *
  69. * @throws \RuntimeException on error.
  70. */
  71. public static function copyToString(StreamInterface $stream, int $maxLen = -1): string
  72. {
  73. $buffer = '';
  74. if ($maxLen === -1) {
  75. while (!$stream->eof()) {
  76. $buf = $stream->read(1048576);
  77. if ($buf === '') {
  78. break;
  79. }
  80. $buffer .= $buf;
  81. }
  82. return $buffer;
  83. }
  84. $len = 0;
  85. while (!$stream->eof() && $len < $maxLen) {
  86. $buf = $stream->read($maxLen - $len);
  87. if ($buf === '') {
  88. break;
  89. }
  90. $buffer .= $buf;
  91. $len = strlen($buffer);
  92. }
  93. return $buffer;
  94. }
  95. /**
  96. * Calculate a hash of a stream.
  97. *
  98. * This method reads the entire stream to calculate a rolling hash, based
  99. * on PHP's `hash_init` functions.
  100. *
  101. * @param StreamInterface $stream Stream to calculate the hash for
  102. * @param string $algo Hash algorithm (e.g. md5, crc32, etc)
  103. * @param bool $rawOutput Whether or not to use raw output
  104. *
  105. * @throws \RuntimeException on error.
  106. */
  107. public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string
  108. {
  109. $pos = $stream->tell();
  110. if ($pos > 0) {
  111. $stream->rewind();
  112. }
  113. $ctx = hash_init($algo);
  114. while (!$stream->eof()) {
  115. hash_update($ctx, $stream->read(1048576));
  116. }
  117. $out = hash_final($ctx, $rawOutput);
  118. $stream->seek($pos);
  119. return $out;
  120. }
  121. /**
  122. * Clone and modify a request with the given changes.
  123. *
  124. * This method is useful for reducing the number of clones needed to mutate
  125. * a message.
  126. *
  127. * The changes can be one of:
  128. * - method: (string) Changes the HTTP method.
  129. * - set_headers: (array) Sets the given headers.
  130. * - remove_headers: (array) Remove the given headers.
  131. * - body: (mixed) Sets the given body.
  132. * - uri: (UriInterface) Set the URI.
  133. * - query: (string) Set the query string value of the URI.
  134. * - version: (string) Set the protocol version.
  135. *
  136. * @param RequestInterface $request Request to clone and modify.
  137. * @param array $changes Changes to apply.
  138. */
  139. public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface
  140. {
  141. if (!$changes) {
  142. return $request;
  143. }
  144. $headers = $request->getHeaders();
  145. if (!isset($changes['uri'])) {
  146. $uri = $request->getUri();
  147. } else {
  148. // Remove the host header if one is on the URI
  149. if ($host = $changes['uri']->getHost()) {
  150. $changes['set_headers']['Host'] = $host;
  151. if ($port = $changes['uri']->getPort()) {
  152. $standardPorts = ['http' => 80, 'https' => 443];
  153. $scheme = $changes['uri']->getScheme();
  154. if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
  155. $changes['set_headers']['Host'] .= ':' . $port;
  156. }
  157. }
  158. }
  159. $uri = $changes['uri'];
  160. }
  161. if (!empty($changes['remove_headers'])) {
  162. $headers = self::caselessRemove($changes['remove_headers'], $headers);
  163. }
  164. if (!empty($changes['set_headers'])) {
  165. $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers);
  166. $headers = $changes['set_headers'] + $headers;
  167. }
  168. if (isset($changes['query'])) {
  169. $uri = $uri->withQuery($changes['query']);
  170. }
  171. if ($request instanceof ServerRequestInterface) {
  172. $new = (new ServerRequest(
  173. $changes['method'] ?? $request->getMethod(),
  174. $uri,
  175. $headers,
  176. $changes['body'] ?? $request->getBody(),
  177. $changes['version'] ?? $request->getProtocolVersion(),
  178. $request->getServerParams()
  179. ))
  180. ->withParsedBody($request->getParsedBody())
  181. ->withQueryParams($request->getQueryParams())
  182. ->withCookieParams($request->getCookieParams())
  183. ->withUploadedFiles($request->getUploadedFiles());
  184. foreach ($request->getAttributes() as $key => $value) {
  185. $new = $new->withAttribute($key, $value);
  186. }
  187. return $new;
  188. }
  189. return new Request(
  190. $changes['method'] ?? $request->getMethod(),
  191. $uri,
  192. $headers,
  193. $changes['body'] ?? $request->getBody(),
  194. $changes['version'] ?? $request->getProtocolVersion()
  195. );
  196. }
  197. /**
  198. * Read a line from the stream up to the maximum allowed buffer length.
  199. *
  200. * @param StreamInterface $stream Stream to read from
  201. * @param int|null $maxLength Maximum buffer length
  202. */
  203. public static function readLine(StreamInterface $stream, ?int $maxLength = null): string
  204. {
  205. $buffer = '';
  206. $size = 0;
  207. while (!$stream->eof()) {
  208. if ('' === ($byte = $stream->read(1))) {
  209. return $buffer;
  210. }
  211. $buffer .= $byte;
  212. // Break when a new line is found or the max length - 1 is reached
  213. if ($byte === "\n" || ++$size === $maxLength - 1) {
  214. break;
  215. }
  216. }
  217. return $buffer;
  218. }
  219. /**
  220. * Create a new stream based on the input type.
  221. *
  222. * Options is an associative array that can contain the following keys:
  223. * - metadata: Array of custom metadata.
  224. * - size: Size of the stream.
  225. *
  226. * This method accepts the following `$resource` types:
  227. * - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
  228. * - `string`: Creates a stream object that uses the given string as the contents.
  229. * - `resource`: Creates a stream object that wraps the given PHP stream resource.
  230. * - `Iterator`: If the provided value implements `Iterator`, then a read-only
  231. * stream object will be created that wraps the given iterable. Each time the
  232. * stream is read from, data from the iterator will fill a buffer and will be
  233. * continuously called until the buffer is equal to the requested read size.
  234. * Subsequent read calls will first read from the buffer and then call `next`
  235. * on the underlying iterator until it is exhausted.
  236. * - `object` with `__toString()`: If the object has the `__toString()` method,
  237. * the object will be cast to a string and then a stream will be returned that
  238. * uses the string value.
  239. * - `NULL`: When `null` is passed, an empty stream object is returned.
  240. * - `callable` When a callable is passed, a read-only stream object will be
  241. * created that invokes the given callable. The callable is invoked with the
  242. * number of suggested bytes to read. The callable can return any number of
  243. * bytes, but MUST return `false` when there is no more data to return. The
  244. * stream object that wraps the callable will invoke the callable until the
  245. * number of requested bytes are available. Any additional bytes will be
  246. * buffered and used in subsequent reads.
  247. *
  248. * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
  249. * @param array{size?: int, metadata?: array} $options Additional options
  250. *
  251. * @throws \InvalidArgumentException if the $resource arg is not valid.
  252. */
  253. public static function streamFor($resource = '', array $options = []): StreamInterface
  254. {
  255. if (is_scalar($resource)) {
  256. $stream = self::tryFopen('php://temp', 'r+');
  257. if ($resource !== '') {
  258. fwrite($stream, (string) $resource);
  259. fseek($stream, 0);
  260. }
  261. return new Stream($stream, $options);
  262. }
  263. switch (gettype($resource)) {
  264. case 'resource':
  265. /*
  266. * The 'php://input' is a special stream with quirks and inconsistencies.
  267. * We avoid using that stream by reading it into php://temp
  268. */
  269. /** @var resource $resource */
  270. if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') {
  271. $stream = self::tryFopen('php://temp', 'w+');
  272. stream_copy_to_stream($resource, $stream);
  273. fseek($stream, 0);
  274. $resource = $stream;
  275. }
  276. return new Stream($resource, $options);
  277. case 'object':
  278. /** @var object $resource */
  279. if ($resource instanceof StreamInterface) {
  280. return $resource;
  281. } elseif ($resource instanceof \Iterator) {
  282. return new PumpStream(function () use ($resource) {
  283. if (!$resource->valid()) {
  284. return false;
  285. }
  286. $result = $resource->current();
  287. $resource->next();
  288. return $result;
  289. }, $options);
  290. } elseif (method_exists($resource, '__toString')) {
  291. return self::streamFor((string) $resource, $options);
  292. }
  293. break;
  294. case 'NULL':
  295. return new Stream(self::tryFopen('php://temp', 'r+'), $options);
  296. }
  297. if (is_callable($resource)) {
  298. return new PumpStream($resource, $options);
  299. }
  300. throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
  301. }
  302. /**
  303. * Safely opens a PHP stream resource using a filename.
  304. *
  305. * When fopen fails, PHP normally raises a warning. This function adds an
  306. * error handler that checks for errors and throws an exception instead.
  307. *
  308. * @param string $filename File to open
  309. * @param string $mode Mode used to open the file
  310. *
  311. * @return resource
  312. *
  313. * @throws \RuntimeException if the file cannot be opened
  314. */
  315. public static function tryFopen(string $filename, string $mode)
  316. {
  317. $ex = null;
  318. set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool {
  319. $ex = new \RuntimeException(sprintf(
  320. 'Unable to open "%s" using mode "%s": %s',
  321. $filename,
  322. $mode,
  323. $errstr
  324. ));
  325. return true;
  326. });
  327. try {
  328. /** @var resource $handle */
  329. $handle = fopen($filename, $mode);
  330. } catch (\Throwable $e) {
  331. $ex = new \RuntimeException(sprintf(
  332. 'Unable to open "%s" using mode "%s": %s',
  333. $filename,
  334. $mode,
  335. $e->getMessage()
  336. ), 0, $e);
  337. }
  338. restore_error_handler();
  339. if ($ex) {
  340. /** @var $ex \RuntimeException */
  341. throw $ex;
  342. }
  343. return $handle;
  344. }
  345. /**
  346. * Safely gets the contents of a given stream.
  347. *
  348. * When stream_get_contents fails, PHP normally raises a warning. This
  349. * function adds an error handler that checks for errors and throws an
  350. * exception instead.
  351. *
  352. * @param resource $stream
  353. *
  354. * @throws \RuntimeException if the stream cannot be read
  355. */
  356. public static function tryGetContents($stream): string
  357. {
  358. $ex = null;
  359. set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool {
  360. $ex = new \RuntimeException(sprintf(
  361. 'Unable to read stream contents: %s',
  362. $errstr
  363. ));
  364. return true;
  365. });
  366. try {
  367. /** @var string|false $contents */
  368. $contents = stream_get_contents($stream);
  369. if ($contents === false) {
  370. $ex = new \RuntimeException('Unable to read stream contents');
  371. }
  372. } catch (\Throwable $e) {
  373. $ex = new \RuntimeException(sprintf(
  374. 'Unable to read stream contents: %s',
  375. $e->getMessage()
  376. ), 0, $e);
  377. }
  378. restore_error_handler();
  379. if ($ex) {
  380. /** @var $ex \RuntimeException */
  381. throw $ex;
  382. }
  383. return $contents;
  384. }
  385. /**
  386. * Returns a UriInterface for the given value.
  387. *
  388. * This function accepts a string or UriInterface and returns a
  389. * UriInterface for the given value. If the value is already a
  390. * UriInterface, it is returned as-is.
  391. *
  392. * @param string|UriInterface $uri
  393. *
  394. * @throws \InvalidArgumentException
  395. */
  396. public static function uriFor($uri): UriInterface
  397. {
  398. if ($uri instanceof UriInterface) {
  399. return $uri;
  400. }
  401. if (is_string($uri)) {
  402. return new Uri($uri);
  403. }
  404. throw new \InvalidArgumentException('URI must be a string or UriInterface');
  405. }
  406. }