[ Index ]

PHP Cross Reference of phpBB-3.3.2-deutsch

title

Body

[close]

/vendor/guzzlehttp/psr7/src/ -> Utils.php (source)

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


Generated: Wed Nov 11 20:28:18 2020 Cross-referenced by PHPXref 0.7.1