2 namespace GuzzleHttp\Psr7;
4 use Psr\Http\Message\StreamInterface;
7 * Provides a buffer stream that can be written to to fill a buffer, and read
8 * from to remove bytes from the buffer.
10 * This stream returns a "hwm" metadata value that tells upstream consumers
11 * what the configured high water mark of the stream is, or the maximum
12 * preferred size of the buffer.
14 class BufferStream implements StreamInterface
20 * @param int $hwm High water mark, representing the preferred maximum
21 * buffer size. If the size of the buffer exceeds the high
22 * water mark, then calls to write will continue to succeed
23 * but will return false to inform writers to slow down
24 * until the buffer has been drained by reading from it.
26 public function __construct($hwm = 16384)
31 public function __toString()
33 return $this->getContents();
36 public function getContents()
38 $buffer = $this->buffer;
44 public function close()
49 public function detach()
54 public function getSize()
56 return strlen($this->buffer);
59 public function isReadable()
64 public function isWritable()
69 public function isSeekable()
74 public function rewind()
79 public function seek($offset, $whence = SEEK_SET)
81 throw new \RuntimeException('Cannot seek a BufferStream');
86 return strlen($this->buffer) === 0;
89 public function tell()
91 throw new \RuntimeException('Cannot determine the position of a BufferStream');
95 * Reads data from the buffer.
97 public function read($length)
99 $currentLength = strlen($this->buffer);
101 if ($length >= $currentLength) {
102 // No need to slice the buffer because we don't have enough data.
103 $result = $this->buffer;
106 // Slice up the result to provide a subset of the buffer.
107 $result = substr($this->buffer, 0, $length);
108 $this->buffer = substr($this->buffer, $length);
115 * Writes data to the buffer.
117 public function write($string)
119 $this->buffer .= $string;
121 // TODO: What should happen here?
122 if (strlen($this->buffer) >= $this->hwm) {
126 return strlen($string);
129 public function getMetadata($key = null)
135 return $key ? null : [];