3 * Zend Framework (http://framework.zend.com/)
5 * @see http://github.com/zendframework/zend-diactoros for the canonical source repository
6 * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
10 namespace Zend\Diactoros;
12 use InvalidArgumentException;
13 use Psr\Http\Message\StreamInterface;
16 use function array_key_exists;
21 * Implementation of PSR HTTP streams
23 class CallbackStream implements StreamInterface
31 * @param callable $callback
32 * @throws InvalidArgumentException
34 public function __construct(callable $callback)
36 $this->attach($callback);
42 public function __toString()
44 return $this->getContents();
50 public function close()
52 $this->callback = null;
58 public function detach()
60 $callback = $this->callback;
61 $this->callback = null;
66 * Attach a new callback to the instance.
68 * @param callable $callback
69 * @throws InvalidArgumentException for callable callback
71 public function attach(callable $callback)
73 $this->callback = $callback;
79 public function getSize()
86 public function tell()
88 throw new RuntimeException('Callback streams cannot tell position');
96 return empty($this->callback);
102 public function isSeekable()
110 public function seek($offset, $whence = SEEK_SET)
112 throw new RuntimeException('Callback streams cannot seek position');
118 public function rewind()
120 throw new RuntimeException('Callback streams cannot rewind position');
126 public function isWritable()
134 public function write($string)
136 throw new RuntimeException('Callback streams cannot write');
142 public function isReadable()
150 public function read($length)
152 throw new RuntimeException('Callback streams cannot read');
158 public function getContents()
160 $callback = $this->detach();
161 return $callback ? $callback() : '';
167 public function getMetadata($key = null)
170 'eof' => $this->eof(),
171 'stream_type' => 'callback',
179 if (! array_key_exists($key, $metadata)) {
183 return $metadata[$key];