| Total Complexity | 11 |
| Total Lines | 41 |
| Duplicated Lines | 0 % |
| Changes | 4 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 13 | class ResourceInputStream implements InputStream |
||
| 14 | { |
||
| 15 | /** |
||
| 16 | * @var resource |
||
| 17 | */ |
||
| 18 | private $stream; |
||
| 19 | |||
| 20 | public function __construct($stream = \STDIN) |
||
| 21 | { |
||
| 22 | if (!is_resource($stream) || get_resource_type($stream) !== 'stream') { |
||
| 23 | throw new \InvalidArgumentException('Expected a valid stream'); |
||
| 24 | } |
||
| 25 | |||
| 26 | $meta = stream_get_meta_data($stream); |
||
| 27 | if (strpos($meta['mode'], 'r') === false && strpos($meta['mode'], '+') === false) { |
||
| 28 | throw new \InvalidArgumentException('Expected a readable stream'); |
||
| 29 | } |
||
| 30 | |||
| 31 | $this->stream = $stream; |
||
| 32 | } |
||
| 33 | |||
| 34 | public function read(int $numBytes, callable $callback) : void |
||
| 35 | { |
||
| 36 | $meta = stream_get_meta_data($this->stream); |
||
| 37 | if ($meta['blocked'] && ($meta['unread_bytes'] > 0)) { |
||
| 38 | stream_set_blocking($this->stream, false); |
||
| 39 | } |
||
| 40 | $buffer = fread($this->stream, $numBytes); |
||
| 41 | if ($meta['blocked'] && ($meta['unread_bytes'] > 0)) { |
||
| 42 | stream_set_blocking($this->stream, true); |
||
| 43 | } |
||
| 44 | |||
| 45 | $callback($buffer); |
||
| 46 | } |
||
| 47 | |||
| 48 | /** |
||
| 49 | * Whether the stream is connected to an interactive terminal |
||
| 50 | */ |
||
| 51 | public function isInteractive() : bool |
||
| 54 | } |
||
| 55 | } |
||
| 56 |