Passed
Pull Request — master (#1)
by Aydin
02:19
created

ResourceInputStream::__construct()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace PhpSchool\Terminal\IO;
4
5
use function is_resource;
6
use function get_resource_type;
7
use function stream_get_meta_data;
8
use function strpos;
9
10
/**
11
 * @author Aydin Hassan <[email protected]>
12
 */
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
        $buffer = fread($this->stream, $numBytes);
37
        $callback($buffer);
38
    }
39
40
    /**
41
     * Whether the stream is connected to an interactive terminal
42
     */
43
    public function isInteractive() : bool
44
    {
45
        return posix_isatty($this->stream);
46
    }
47
}
48