2 namespace GuzzleHttp\Psr7;
4 use Psr\Http\Message\StreamInterface;
7 * Stream decorator trait
8 * @property StreamInterface stream
10 trait StreamDecoratorTrait
13 * @param StreamInterface $stream Stream to decorate
15 public function __construct(StreamInterface $stream)
17 $this->stream = $stream;
21 * Magic method used to create a new stream if streams are not added in
22 * the constructor of a decorator (e.g., LazyOpenStream).
24 * @param string $name Name of the property (allows "stream" only).
26 * @return StreamInterface
28 public function __get($name)
30 if ($name == 'stream') {
31 $this->stream = $this->createStream();
35 throw new \UnexpectedValueException("$name not found on class");
38 public function __toString()
41 if ($this->isSeekable()) {
44 return $this->getContents();
45 } catch (\Exception $e) {
46 // Really, PHP? https://bugs.php.net/bug.php?id=53648
47 trigger_error('StreamDecorator::__toString exception: '
48 . (string) $e, E_USER_ERROR);
53 public function getContents()
55 return copy_to_string($this);
59 * Allow decorators to implement custom methods
61 * @param string $method Missing method name
62 * @param array $args Method arguments
66 public function __call($method, array $args)
68 $result = call_user_func_array([$this->stream, $method], $args);
70 // Always return the wrapped object if the result is a return $this
71 return $result === $this->stream ? $this : $result;
74 public function close()
76 $this->stream->close();
79 public function getMetadata($key = null)
81 return $this->stream->getMetadata($key);
84 public function detach()
86 return $this->stream->detach();
89 public function getSize()
91 return $this->stream->getSize();
96 return $this->stream->eof();
99 public function tell()
101 return $this->stream->tell();
104 public function isReadable()
106 return $this->stream->isReadable();
109 public function isWritable()
111 return $this->stream->isWritable();
114 public function isSeekable()
116 return $this->stream->isSeekable();
119 public function rewind()
124 public function seek($offset, $whence = SEEK_SET)
126 $this->stream->seek($offset, $whence);
129 public function read($length)
131 return $this->stream->read($length);
134 public function write($string)
136 return $this->stream->write($string);
140 * Implement in subclasses to dynamically create streams when requested.
142 * @return StreamInterface
143 * @throws \BadMethodCallException
145 protected function createStream()
147 throw new \BadMethodCallException('Not implemented');