Utils.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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|int)[] $keys
  14. */
  15. public static function caselessRemove(array $keys, array $data): array
  16. {
  17. $result = [];
  18. foreach ($keys as &$key) {
  19. $key = strtolower((string) $key);
  20. }
  21. foreach ($data as $k => $v) {
  22. if (!in_array(strtolower((string) $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. * Redact the password in the user info part of a URI.
  221. */
  222. public static function redactUserInfo(UriInterface $uri): UriInterface
  223. {
  224. $userInfo = $uri->getUserInfo();
  225. if (false !== ($pos = \strpos($userInfo, ':'))) {
  226. return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***');
  227. }
  228. return $uri;
  229. }
  230. /**
  231. * Create a new stream based on the input type.
  232. *
  233. * Options is an associative array that can contain the following keys:
  234. * - metadata: Array of custom metadata.
  235. * - size: Size of the stream.
  236. *
  237. * This method accepts the following `$resource` types:
  238. * - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
  239. * - `string`: Creates a stream object that uses the given string as the contents.
  240. * - `resource`: Creates a stream object that wraps the given PHP stream resource.
  241. * - `Iterator`: If the provided value implements `Iterator`, then a read-only
  242. * stream object will be created that wraps the given iterable. Each time the
  243. * stream is read from, data from the iterator will fill a buffer and will be
  244. * continuously called until the buffer is equal to the requested read size.
  245. * Subsequent read calls will first read from the buffer and then call `next`
  246. * on the underlying iterator until it is exhausted.
  247. * - `object` with `__toString()`: If the object has the `__toString()` method,
  248. * the object will be cast to a string and then a stream will be returned that
  249. * uses the string value.
  250. * - `NULL`: When `null` is passed, an empty stream object is returned.
  251. * - `callable` When a callable is passed, a read-only stream object will be
  252. * created that invokes the given callable. The callable is invoked with the
  253. * number of suggested bytes to read. The callable can return any number of
  254. * bytes, but MUST return `false` when there is no more data to return. The
  255. * stream object that wraps the callable will invoke the callable until the
  256. * number of requested bytes are available. Any additional bytes will be
  257. * buffered and used in subsequent reads.
  258. *
  259. * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
  260. * @param array{size?: int, metadata?: array} $options Additional options
  261. *
  262. * @throws \InvalidArgumentException if the $resource arg is not valid.
  263. */
  264. public static function streamFor($resource = '', array $options = []): StreamInterface
  265. {
  266. if (is_scalar($resource)) {
  267. $stream = self::tryFopen('php://temp', 'r+');
  268. if ($resource !== '') {
  269. fwrite($stream, (string) $resource);
  270. fseek($stream, 0);
  271. }
  272. return new Stream($stream, $options);
  273. }
  274. switch (gettype($resource)) {
  275. case 'resource':
  276. /*
  277. * The 'php://input' is a special stream with quirks and inconsistencies.
  278. * We avoid using that stream by reading it into php://temp
  279. */
  280. /** @var resource $resource */
  281. if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') {
  282. $stream = self::tryFopen('php://temp', 'w+');
  283. stream_copy_to_stream($resource, $stream);
  284. fseek($stream, 0);
  285. $resource = $stream;
  286. }
  287. return new Stream($resource, $options);
  288. case 'object':
  289. /** @var object $resource */
  290. if ($resource instanceof StreamInterface) {
  291. return $resource;
  292. } elseif ($resource instanceof \Iterator) {
  293. return new PumpStream(function () use ($resource) {
  294. if (!$resource->valid()) {
  295. return false;
  296. }
  297. $result = $resource->current();
  298. $resource->next();
  299. return $result;
  300. }, $options);
  301. } elseif (method_exists($resource, '__toString')) {
  302. return self::streamFor((string) $resource, $options);
  303. }
  304. break;
  305. case 'NULL':
  306. return new Stream(self::tryFopen('php://temp', 'r+'), $options);
  307. }
  308. if (is_callable($resource)) {
  309. return new PumpStream($resource, $options);
  310. }
  311. throw new \InvalidArgumentException('Invalid resource type: '.gettype($resource));
  312. }
  313. /**
  314. * Safely opens a PHP stream resource using a filename.
  315. *
  316. * When fopen fails, PHP normally raises a warning. This function adds an
  317. * error handler that checks for errors and throws an exception instead.
  318. *
  319. * @param string $filename File to open
  320. * @param string $mode Mode used to open the file
  321. *
  322. * @return resource
  323. *
  324. * @throws \RuntimeException if the file cannot be opened
  325. */
  326. public static function tryFopen(string $filename, string $mode)
  327. {
  328. $ex = null;
  329. set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool {
  330. $ex = new \RuntimeException(sprintf(
  331. 'Unable to open "%s" using mode "%s": %s',
  332. $filename,
  333. $mode,
  334. $errstr
  335. ));
  336. return true;
  337. });
  338. try {
  339. /** @var resource $handle */
  340. $handle = fopen($filename, $mode);
  341. } catch (\Throwable $e) {
  342. $ex = new \RuntimeException(sprintf(
  343. 'Unable to open "%s" using mode "%s": %s',
  344. $filename,
  345. $mode,
  346. $e->getMessage()
  347. ), 0, $e);
  348. }
  349. restore_error_handler();
  350. if ($ex) {
  351. /** @var $ex \RuntimeException */
  352. throw $ex;
  353. }
  354. return $handle;
  355. }
  356. /**
  357. * Safely gets the contents of a given stream.
  358. *
  359. * When stream_get_contents fails, PHP normally raises a warning. This
  360. * function adds an error handler that checks for errors and throws an
  361. * exception instead.
  362. *
  363. * @param resource $stream
  364. *
  365. * @throws \RuntimeException if the stream cannot be read
  366. */
  367. public static function tryGetContents($stream): string
  368. {
  369. $ex = null;
  370. set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool {
  371. $ex = new \RuntimeException(sprintf(
  372. 'Unable to read stream contents: %s',
  373. $errstr
  374. ));
  375. return true;
  376. });
  377. try {
  378. /** @var string|false $contents */
  379. $contents = stream_get_contents($stream);
  380. if ($contents === false) {
  381. $ex = new \RuntimeException('Unable to read stream contents');
  382. }
  383. } catch (\Throwable $e) {
  384. $ex = new \RuntimeException(sprintf(
  385. 'Unable to read stream contents: %s',
  386. $e->getMessage()
  387. ), 0, $e);
  388. }
  389. restore_error_handler();
  390. if ($ex) {
  391. /** @var $ex \RuntimeException */
  392. throw $ex;
  393. }
  394. return $contents;
  395. }
  396. /**
  397. * Returns a UriInterface for the given value.
  398. *
  399. * This function accepts a string or UriInterface and returns a
  400. * UriInterface for the given value. If the value is already a
  401. * UriInterface, it is returned as-is.
  402. *
  403. * @param string|UriInterface $uri
  404. *
  405. * @throws \InvalidArgumentException
  406. */
  407. public static function uriFor($uri): UriInterface
  408. {
  409. if ($uri instanceof UriInterface) {
  410. return $uri;
  411. }
  412. if (is_string($uri)) {
  413. return new Uri($uri);
  414. }
  415. throw new \InvalidArgumentException('URI must be a string or UriInterface');
  416. }
  417. }