3 namespace MediaWiki\Rest
;
6 * A stream class which uses a string as the underlying storage. Surprisingly,
7 * Guzzle does not appear to have one of these. BufferStream does not do what
10 * The normal use of this class should be to first write to the stream, then
11 * rewind, then read back the whole buffer with getContents().
13 * Seeking is supported, however seeking past the end of the string does not
14 * fill with null bytes as in a real file, it throws an exception instead.
16 class StringStream
implements CopyableStreamInterface
{
17 private $contents = '';
21 * Construct a StringStream with the given contents.
23 * The offset will start at 0, ready for reading. If appending to the
24 * given string is desired, you should first seek to the end.
26 * @param string $contents
28 public function __construct( $contents = '' ) {
29 $this->contents
= $contents;
32 public function copyToStream( $stream ) {
33 fwrite( $stream, $this->getContents() );
36 public function __toString() {
37 return $this->contents
;
40 public function close() {
43 public function detach() {
47 public function getSize() {
48 return strlen( $this->contents
);
51 public function tell() {
55 public function eof() {
56 return $this->offset
>= strlen( $this->contents
);
59 public function isSeekable() {
63 public function seek( $offset, $whence = SEEK_SET
) {
66 $this->offset
= $offset;
70 $this->offset +
= $offset;
74 $this->offset
= strlen( $this->contents
) +
$offset;
78 throw new \
InvalidArgumentException( "Invalid value for \$whence" );
80 if ( $this->offset
> strlen( $this->contents
) ) {
81 throw new \
InvalidArgumentException( "Cannot seek beyond the end of a StringStream" );
83 if ( $this->offset
< 0 ) {
84 throw new \
InvalidArgumentException( "Cannot seek before the start of a StringStream" );
88 public function rewind() {
92 public function isWritable() {
96 public function write( $string ) {
97 if ( $this->offset
=== strlen( $this->contents
) ) {
98 $this->contents
.= $string;
100 $this->contents
= substr_replace( $this->contents
, $string,
101 $this->offset
, strlen( $string ) );
103 $this->offset +
= strlen( $string );
104 return strlen( $string );
107 public function isReadable() {
111 public function read( $length ) {
112 if ( $this->offset
=== 0 && $length >= strlen( $this->contents
) ) {
113 $ret = $this->contents
;
114 } elseif ( $this->offset
>= strlen( $this->contents
) ) {
117 $ret = substr( $this->contents
, $this->offset
, $length );
119 $this->offset +
= strlen( $ret );
123 public function getContents() {
124 if ( $this->offset
=== 0 ) {
125 $ret = $this->contents
;
126 } elseif ( $this->offset
>= strlen( $this->contents
) ) {
129 $ret = substr( $this->contents
, $this->offset
);
131 $this->offset
= strlen( $this->contents
);
135 public function getMetadata( $key = null ) {