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 if ( $this->offset
!== 0 ) {
34 $block = substr( $this->contents
, $this->offset
);
36 $block = $this->contents
;
38 $this->offset
= strlen( $this->contents
);
39 fwrite( $stream, $block );
42 public function __toString() {
43 return $this->contents
;
46 public function close() {
49 public function detach() {
53 public function getSize() {
54 return strlen( $this->contents
);
57 public function tell() {
61 public function eof() {
62 return $this->offset
>= strlen( $this->contents
);
65 public function isSeekable() {
69 public function seek( $offset, $whence = SEEK_SET
) {
72 $this->offset
= $offset;
76 $this->offset +
= $offset;
80 $this->offset
= strlen( $this->contents
) +
$offset;
84 throw new \
InvalidArgumentException( "Invalid value for \$whence" );
86 if ( $this->offset
> strlen( $this->contents
) ) {
87 throw new \
InvalidArgumentException( "Cannot seek beyond the end of a StringStream" );
89 if ( $this->offset
< 0 ) {
90 throw new \
InvalidArgumentException( "Cannot seek before the start of a StringStream" );
94 public function rewind() {
98 public function isWritable() {
102 public function write( $string ) {
103 if ( $this->offset
=== strlen( $this->contents
) ) {
104 $this->contents
.= $string;
106 $this->contents
= substr_replace( $this->contents
, $string,
107 $this->offset
, strlen( $string ) );
109 $this->offset +
= strlen( $string );
110 return strlen( $string );
113 public function isReadable() {
117 public function read( $length ) {
118 if ( $this->offset
=== 0 && $length >= strlen( $this->contents
) ) {
119 $ret = $this->contents
;
121 $ret = substr( $this->contents
, $this->offset
, $length );
123 $this->offset +
= strlen( $ret );
127 public function getContents() {
128 if ( $this->offset
=== 0 ) {
129 $ret = $this->contents
;
131 $ret = substr( $this->contents
, $this->offset
);
133 $this->offset
= strlen( $this->contents
);
137 public function getMetadata( $key = null ) {