@@ -35,23 +35,7 @@ class Stream implements StreamInterface
3535 */
3636 public function __construct ($ stream , $ mode = 'r ' )
3737 {
38- $ this ->stream = $ stream ;
39-
40- if (is_resource ($ stream )) {
41- $ this ->resource = $ stream ;
42- } elseif (is_string ($ stream )) {
43- set_error_handler (function ($ errno , $ errstr ) {
44- throw new InvalidArgumentException (
45- 'Invalid file provided for stream; must be a valid path with valid permissions '
46- );
47- }, E_WARNING );
48- $ this ->resource = fopen ($ stream , $ mode );
49- restore_error_handler ();
50- } else {
51- throw new InvalidArgumentException (
52- 'Invalid stream provided; must be a string stream identifier or resource '
53- );
54- }
38+ $ this ->setStream ($ stream , $ mode );
5539 }
5640
5741 /**
@@ -105,26 +89,7 @@ public function detach()
10589 */
10690 public function attach ($ resource , $ mode = 'r ' )
10791 {
108- $ error = null ;
109- if (! is_resource ($ resource ) && is_string ($ resource )) {
110- set_error_handler (function ($ e ) use (&$ error ) {
111- $ error = $ e ;
112- }, E_WARNING );
113- $ resource = fopen ($ resource , $ mode );
114- restore_error_handler ();
115- }
116-
117- if ($ error ) {
118- throw new InvalidArgumentException ('Invalid stream reference provided ' );
119- }
120-
121- if (! is_resource ($ resource )) {
122- throw new InvalidArgumentException (
123- 'Invalid stream provided; must be a string stream identifier or resource '
124- );
125- }
126-
127- $ this ->resource = $ resource ;
92+ $ this ->setStream ($ resource , $ mode );
12893 }
12994
13095 /**
@@ -323,4 +288,41 @@ public function getMetadata($key = null)
323288
324289 return $ metadata [$ key ];
325290 }
291+
292+ /**
293+ * Set the internal stream resource.
294+ *
295+ * @param string|resource $stream String stream target or stream resource.
296+ * @param string $mode Resource mode for stream target.
297+ * @throws InvalidArgumentException for invalid streams or resources.
298+ */
299+ private function setStream ($ stream , $ mode = 'r ' )
300+ {
301+ $ error = null ;
302+ $ resource = $ stream ;
303+
304+ if (is_string ($ stream )) {
305+ set_error_handler (function ($ e ) use (&$ error ) {
306+ $ error = $ e ;
307+ }, E_WARNING );
308+ $ resource = fopen ($ stream , $ mode );
309+ restore_error_handler ();
310+ }
311+
312+ if ($ error ) {
313+ throw new InvalidArgumentException ('Invalid stream reference provided ' );
314+ }
315+
316+ if (! is_resource ($ resource ) || 'stream ' !== get_resource_type ($ resource )) {
317+ throw new InvalidArgumentException (
318+ 'Invalid stream provided; must be a string stream identifier or stream resource '
319+ );
320+ }
321+
322+ if ($ stream !== $ resource ) {
323+ $ this ->stream = $ stream ;
324+ }
325+
326+ $ this ->resource = $ resource ;
327+ }
326328}
0 commit comments