Completed
Push — version-4-wip ( 86a2b9...5c3ca2 )
by Craig
03:49
created

Stream::line()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace League\CLImate\Util\Reader;
4
5
use League\CLImate\Exceptions\RuntimeException;
6
use Seld\CliPrompt\CliPrompt;
7
8
class Stream implements ReaderInterface
9
{
10
    /**
11
     * @var string $filename The name of the file this stream represents.
12
     */
13
    private $filename;
14
15
    /**
16
     * @var resource $resource The underlying stream this object represents.
17
     */
18
    private $resource;
19
20
21
    /**
22
     * Create a new instance.
23
     *
24
     * @param string $filename The name of the file this stream represents
25
     */
26 16
    public function __construct($filename)
27
    {
28 16
        $this->filename = $filename;
29 16
    }
30
31
32
    /**
33
     * Read a line from the stream
34
     *
35
     * @return string
36
     */
37 8
    public function line()
38
    {
39 8
        return trim(fgets($this->getResource(), 1024));
40
    }
41
42
43
    /**
44
     * Read from the stream until EOF (^D) is reached
45
     *
46
     * @return string
47
     */
48 8
    public function multiLine()
49
    {
50 8
        return trim(stream_get_contents($this->getResource()));
51
    }
52
53
54
    /**
55
     * Read one character
56
     *
57
     * @param int $count
58
     *
59
     * @return string
60
     */
61 4
    public function char($count = 1)
62
    {
63 4
        return fread($this->getResource(), $count);
64
    }
65
66
67
    /**
68
     * Read the line, but hide what the user is typing
69
     *
70
     * @return string
71
     */
72
    public function hidden()
73
    {
74
        return CliPrompt::hiddenPrompt();
75
    }
76
77
78
    /**
79
     * Return a valid resource, even if it previously EOF'ed.
80
     *
81
     * @return resource
82
     */
83 16
    private function getResource()
84
    {
85 16
        if ($this->resource && !feof($this->resource)) {
86 4
            return $this->resource;
87
        }
88
89 16
        if ($this->resource !== null) {
90 4
            fclose($this->resource);
91
        }
92
93 16
        $this->resource = fopen($this->filename, "r");
94 16
        if (!$this->resource) {
95
            throw new RuntimeException("Unable to read from {$this->filename}");
96
        }
97
98 16
        return $this->resource;
99
    }
100
}
101