Completed
Push — master ( dd1955...c3a87b )
by Michael
10s
created

ResourceOutputStream   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
dl 0
loc 32
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isInteractive() 0 3 1
A write() 0 3 1
B __construct() 0 12 5
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 ResourceOutputStream implements OutputStream
14
{
15
    /**
16
     * @var resource
17
     */
18
    private $stream;
19
20
    public function __construct($stream = STDOUT)
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 writable stream');
29
        }
30
31
        $this->stream = $stream;
32
    }
33
34
    public function write(string $buffer): void
35
    {
36
        fwrite($this->stream, $buffer);
37
    }
38
39
    /**
40
     * Whether the stream is connected to an interactive terminal
41
     */
42
    public function isInteractive() : bool
43
    {
44
        return posix_isatty($this->stream);
45
    }
46
}
47