1: <?php
2:
3: namespace PHPixie\HTTP\Messages\Stream;
4:
5: use Psr\Http\Message\StreamInterface;
6: use RuntimeException;
7:
8: /**
9: * PSR-7 String stream
10: */
11: class StringStream implements StreamInterface
12: {
13: /**
14: * @var string
15: */
16: protected $string;
17:
18: /**
19: * Constructor
20: * @param string $string
21: */
22: public function __construct($string = '')
23: {
24: $this->string = $string;
25: }
26:
27: /**
28: * @inheritdoc
29: */
30: public function __toString()
31: {
32: return (string) $this->string;
33: }
34:
35: /**
36: * @inheritdoc
37: */
38: public function close()
39: {
40: $this->detach();
41: }
42:
43: /**
44: * @inheritdoc
45: */
46: public function detach()
47: {
48: $this->string = null;
49: return null;
50: }
51:
52: /**
53: * @inheritdoc
54: */
55: public function getSize()
56: {
57: if($this->string === null) {
58: return null;
59: }
60:
61: return mb_strlen($this->string, '8bit');
62: }
63:
64: /**
65: * @inheritdoc
66: */
67: public function tell()
68: {
69: $this->assertNotDetached();
70: return $this->getSize();
71: }
72:
73: /**
74: * @inheritdoc
75: */
76: public function eof()
77: {
78: return true;
79: }
80:
81: /**
82: * @inheritdoc
83: */
84: public function isSeekable()
85: {
86: return false;
87: }
88:
89: /**
90: * @inheritdoc
91: */
92: public function isWritable()
93: {
94: if($this->string === null) {
95: return false;
96: }
97:
98: return true;
99: }
100:
101: /**
102: * @inheritdoc
103: */
104: public function isReadable()
105: {
106: if($this->string === null) {
107: return false;
108: }
109:
110: return true;
111: }
112:
113: /**
114: * @inheritdoc
115: */
116: public function seek($offset, $whence = SEEK_SET)
117: {
118: throw new RuntimeException("String streams are not seakable");
119: }
120:
121: /**
122: * @inheritdoc
123: */
124: public function rewind()
125: {
126: $this->seek(0);
127: }
128:
129: /**
130: * @inheritdoc
131: */
132: public function write($string)
133: {
134: $this->assertNotDetached();
135: $this->string.= $string;
136: }
137:
138: /**
139: * @inheritdoc
140: */
141: public function read($length)
142: {
143: $this->assertNotDetached();
144: return '';
145: }
146:
147: /**
148: * @inheritdoc
149: */
150: public function getContents()
151: {
152: $this->assertNotDetached();
153: return '';
154: }
155:
156: /**
157: * @inheritdoc
158: */
159: public function getMetadata($key = null)
160: {
161: return $key === null ? array() : null;
162: }
163:
164: /**
165: * @throws RuntimeException If stream has been detached
166: */
167: protected function assertNotDetached()
168: {
169: if($this->string === null) {
170: throw new RuntimeException("The stream has been detached");
171: }
172: }
173: }