Completed
Pull Request — master (#1867)
by
unknown
02:27
created

Stream::__construct()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 2
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
1
<?php
2
namespace GuzzleHttp\Psr7;
3
4
use Psr\Http\Message\StreamInterface;
5
6
/**
7
 * PHP stream implementation.
8
 *
9
 * @var $stream
10
 */
11
class Stream implements StreamInterface
12
{
13
    private $stream;
14
    private $size;
15
    private $seekable;
16
    private $readable;
17
    private $writable;
18
    private $uri;
19
    private $customMetadata;
20
21
    /** @var array Hash of readable and writable stream types */
22
    private static $readWriteHash = [
23
        'read' => [
24
            'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
25
            'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
26
            'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
27
            'x+t' => true, 'c+t' => true, 'a+' => true, 'rb+' => true,
28
        ],
29
        'write' => [
30
            'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
31
            'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true, 'rb+' => true,
32
            'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
33
            'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true
34
        ]
35
    ];
36
37
    /**
38
     * This constructor accepts an associative array of options.
39
     *
40
     * - size: (int) If a read stream would otherwise have an indeterminate
41
     *   size, but the size is known due to foreknowledge, then you can
42
     *   provide that size, in bytes.
43
     * - metadata: (array) Any additional metadata to return when the metadata
44
     *   of the stream is accessed.
45
     *
46
     * @param resource $stream  Stream resource to wrap.
47
     * @param array    $options Associative array of options.
48
     *
49
     * @throws \InvalidArgumentException if the stream is not a stream resource
50
     */
51
    public function __construct($stream, $options = [])
52
    {
53
        if (!is_resource($stream)) {
54
            throw new \InvalidArgumentException('Stream must be a resource');
55
        }
56
57
        if (isset($options['size'])) {
58
            $this->size = $options['size'];
59
        }
60
61
        $this->customMetadata = isset($options['metadata'])
62
            ? $options['metadata']
63
            : [];
64
65
        $this->stream = $stream;
66
        $meta = stream_get_meta_data($this->stream);
67
        $this->seekable = $meta['seekable'];
68
        $this->readable = isset(self::$readWriteHash['read'][$meta['mode']]);
69
        $this->writable = isset(self::$readWriteHash['write'][$meta['mode']]);
70
        $this->uri = $this->getMetadata('uri');
71
    }
72
73
    /**
74
     * Closes the stream when the destructed
75
     */
76
    public function __destruct()
77
    {
78
        $this->close();
79
    }
80
81
    public function __toString()
82
    {
83
        try {
84
            $this->seek(0);
85
            return (string) stream_get_contents($this->stream);
86
        } catch (\Exception $e) {
87
            return '';
88
        }
89
    }
90
91
    public function getContents()
92
    {
93
        if (!isset($this->stream)) {
94
            throw new \RuntimeException('Stream is detached');
95
        }
96
97
        $contents = stream_get_contents($this->stream);
98
99
        if ($contents === false) {
100
            throw new \RuntimeException('Unable to read stream contents');
101
        }
102
103
        return $contents;
104
    }
105
106
    public function close()
107
    {
108
        if (isset($this->stream)) {
109
            if (is_resource($this->stream)) {
110
                fclose($this->stream);
111
            }
112
            $this->detach();
113
        }
114
    }
115
116
    public function detach()
117
    {
118
        if (!isset($this->stream)) {
119
            return null;
120
        }
121
122
        $result = $this->stream;
123
        unset($this->stream);
124
        $this->size = $this->uri = null;
125
        $this->readable = $this->writable = $this->seekable = false;
126
127
        return $result;
128
    }
129
130
    public function getSize()
131
    {
132
        if ($this->size !== null) {
133
            return $this->size;
134
        }
135
136
        if (!isset($this->stream)) {
137
            return null;
138
        }
139
140
        // Clear the stat cache if the stream has a URI
141
        if ($this->uri) {
142
            clearstatcache(true, $this->uri);
143
        }
144
145
        $stats = fstat($this->stream);
146
        if (isset($stats['size'])) {
147
            $this->size = $stats['size'];
148
            return $this->size;
149
        }
150
151
        return null;
152
    }
153
154
    public function isReadable()
155
    {
156
        return $this->readable;
157
    }
158
159
    public function isWritable()
160
    {
161
        return $this->writable;
162
    }
163
164
    public function isSeekable()
165
    {
166
        return $this->seekable;
167
    }
168
169
    public function eof()
170
    {
171
        if (!isset($this->stream)) {
172
            throw new \RuntimeException('Stream is detached');
173
        }
174
175
        return feof($this->stream);
176
    }
177
178
    public function tell()
179
    {
180
        if (!isset($this->stream)) {
181
            throw new \RuntimeException('Stream is detached');
182
        }
183
184
        $result = ftell($this->stream);
185
186
        if ($result === false) {
187
            throw new \RuntimeException('Unable to determine stream position');
188
        }
189
190
        return $result;
191
    }
192
193
    public function rewind()
194
    {
195
        $this->seek(0);
196
    }
197
198
    public function seek($offset, $whence = SEEK_SET)
199
    {
200
        if (!isset($this->stream)) {
201
            throw new \RuntimeException('Stream is detached');
202
        }
203
        if (!$this->seekable) {
204
            throw new \RuntimeException('Stream is not seekable');
205
        }
206
        if (fseek($this->stream, $offset, $whence) === -1) {
207
            throw new \RuntimeException('Unable to seek to stream position '
208
                . $offset . ' with whence ' . var_export($whence, true));
209
        }
210
    }
211
212
    public function read($length)
213
    {
214
        if (!isset($this->stream)) {
215
            throw new \RuntimeException('Stream is detached');
216
        }
217
        if (!$this->readable) {
218
            throw new \RuntimeException('Cannot read from non-readable stream');
219
        }
220
        if ($length < 0) {
221
            throw new \RuntimeException('Length parameter cannot be negative');
222
        }
223
224
        if (0 === $length) {
225
            return '';
226
        }
227
228
        $string = fread($this->stream, $length);
229
        if (false === $string) {
230
            throw new \RuntimeException('Unable to read from stream');
231
        }
232
233
        return $string;
234
    }
235
236
    public function write($string)
237
    {
238
        if (!isset($this->stream)) {
239
            throw new \RuntimeException('Stream is detached');
240
        }
241
        if (!$this->writable) {
242
            throw new \RuntimeException('Cannot write to a non-writable stream');
243
        }
244
245
        // We can't know the size after writing anything
246
        $this->size = null;
247
        $result = fwrite($this->stream, $string);
248
249
        if ($result === false) {
250
            throw new \RuntimeException('Unable to write to stream');
251
        }
252
253
        return $result;
254
    }
255
256
    public function getMetadata($key = null)
257
    {
258
        if (!isset($this->stream)) {
259
            return $key ? null : [];
260
        } elseif (!$key) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $key of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
261
            return $this->customMetadata + stream_get_meta_data($this->stream);
262
        } elseif (isset($this->customMetadata[$key])) {
263
            return $this->customMetadata[$key];
264
        }
265
266
        $meta = stream_get_meta_data($this->stream);
267
268
        return isset($meta[$key]) ? $meta[$key] : null;
269
    }
270
}
271