Completed
Pull Request — master (#80)
by Aydin
01:51
created

ResourceInputStream::read()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace PhpSchool\CliMenu\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 View Code Duplication
    public function __construct($stream = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
21
    {
22
        if ($stream === null) {
23
            $stream = STDIN;
24
        }
25
26
        if (!is_resource($stream) || get_resource_type($stream) !== 'stream') {
27
            throw new \InvalidArgumentException('Expected a valid stream');
28
        }
29
30
        $meta = stream_get_meta_data($stream);
31
        if (strpos($meta['mode'], 'r') === false && strpos($meta['mode'], '+') === false) {
32
            throw new \InvalidArgumentException('Expected a readable stream');
33
        }
34
35
        $this->stream = $stream;
36
    }
37
38
    public function read(int $numBytes, callable $callback) : void
39
    {
40
        $buffer = fread($this->stream, $numBytes);
41
        $callback($buffer);
42
    }
43
}
44