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