namespace GuzzleHttp\Psr7;
use Psr\Http\Message\StreamInterface;
* Converts Guzzle streams into PHP stream resources.
/** @var StreamInterface */
/** @var string r, r+, or w */
* Returns a resource representing the stream.
* @param StreamInterface $stream The stream to get a resource for
* @throws \InvalidArgumentException if stream is not readable or writable
public static function getResource(StreamInterface $stream)
if ($stream->isReadable()) {
$mode = $stream->isWritable() ? 'r+' : 'r';
} elseif ($stream->isWritable()) {
throw new \InvalidArgumentException('The stream must be readable, '
return fopen('guzzle://stream', $mode, null, self::createStreamContext($stream));
* Creates a stream context that can be used to open a stream as a php stream resource.
* @param StreamInterface $stream
public static function createStreamContext(StreamInterface $stream)
return stream_context_create([
'guzzle' => ['stream' => $stream]
* Registers the stream wrapper if needed
public static function register()
if (!in_array('guzzle', stream_get_wrappers())) {
stream_wrapper_register('guzzle', __CLASS__);
public function stream_open($path, $mode, $options, &$opened_path)
$options = stream_context_get_options($this->context);
if (!isset($options['guzzle']['stream'])) {
$this->stream = $options['guzzle']['stream'];
public function stream_read($count)
return $this->stream->read($count);
public function stream_write($data)
return (int) $this->stream->write($data);
public function stream_tell()
return $this->stream->tell();
public function stream_eof()
return $this->stream->eof();
public function stream_seek($offset, $whence)
$this->stream->seek($offset, $whence);
public function stream_cast($cast_as)
$stream = clone($this->stream);
return $stream->detach();
public function stream_stat()
'mode' => $modeMap[$this->mode],
'size' => $this->stream->getSize() ?: 0,
public function url_stat($path, $flags)