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 fwrite( $stream, $block );
41 public function __toString() {
42 return $this->contents
;
45 public function close() {
48 public function detach() {
52 public function getSize() {
53 return strlen( $this->contents
);
56 public function tell() {
60 public function eof() {
61 return $this->offset
>= strlen( $this->contents
);
64 public function isSeekable() {
68 public function seek( $offset, $whence = SEEK_SET
) {
71 $this->offset
= $offset;
75 $this->offset +
= $offset;
79 $this->offset
= strlen( $this->contents
) +
$offset;
83 throw new \
InvalidArgumentException( "Invalid value for \$whence" );
85 if ( $this->offset
> strlen( $this->contents
) ) {
86 throw new \
InvalidArgumentException( "Cannot seek beyond the end of a StringStream" );
88 if ( $this->offset
< 0 ) {
89 throw new \
InvalidArgumentException( "Cannot seek before the start of a StringStream" );
93 public function rewind() {
97 public function isWritable() {
101 public function write( $string ) {
102 if ( $this->offset
=== strlen( $this->contents
) ) {
103 $this->contents
.= $string;
105 $this->contents
= substr_replace( $this->contents
, $string,
106 $this->offset
, strlen( $string ) );
108 $this->offset +
= strlen( $string );
109 return strlen( $string );
112 public function isReadable() {
116 public function read( $length ) {
117 if ( $this->offset
=== 0 && $length >= strlen( $this->contents
) ) {
118 $ret = $this->contents
;
120 $ret = substr( $this->contents
, $this->offset
, $length );
122 $this->offset +
= strlen( $ret );
126 public function getContents() {
127 if ( $this->offset
=== 0 ) {
128 $ret = $this->contents
;
130 $ret = substr( $this->contents
, $this->offset
);
132 $this->offset
= strlen( $this->contents
);
136 public function getMetadata( $key = null ) {