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;
14 use Psr\Http\Message\StreamInterface;
17 * Implementation of PSR HTTP streams
19 class CallbackStream implements StreamInterface
27 * @param callable $callback
28 * @throws InvalidArgumentException
30 public function __construct(callable $callback)
32 $this->attach($callback);
38 public function __toString()
40 return $this->getContents();
46 public function close()
48 $this->callback = null;
54 public function detach()
56 $callback = $this->callback;
57 $this->callback = null;
62 * Attach a new callback to the instance.
64 * @param callable $callback
65 * @throws InvalidArgumentException for callable callback
67 public function attach(callable $callback)
69 $this->callback = $callback;
75 public function getSize()
82 public function tell()
84 throw new RuntimeException('Callback streams cannot tell position');
92 return empty($this->callback);
98 public function isSeekable()
106 public function seek($offset, $whence = SEEK_SET)
108 throw new RuntimeException('Callback streams cannot seek position');
114 public function rewind()
116 throw new RuntimeException('Callback streams cannot rewind position');
122 public function isWritable()
130 public function write($string)
132 throw new RuntimeException('Callback streams cannot write');
138 public function isReadable()
146 public function read($length)
148 throw new RuntimeException('Callback streams cannot read');
154 public function getContents()
156 $callback = $this->detach();
157 return $callback ? $callback() : '';
163 public function getMetadata($key = null)
166 'eof' => $this->eof(),
167 'stream_type' => 'callback',
175 if (! array_key_exists($key, $metadata)) {
179 return $metadata[$key];