Stdin::getStdIn()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.5923

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 4
cts 6
cp 0.6667
rs 9.7998
c 0
b 0
f 0
cc 4
nc 3
nop 0
crap 4.5923
1
<?php
2
3
namespace League\CLImate\Util\Reader;
4
5
use League\CLImate\Exceptions\RuntimeException;
6
use Seld\CliPrompt\CliPrompt;
7
8
class Stdin implements ReaderInterface
9
{
10
    protected $stdIn = false;
11
12
    /**
13
     * Read the line typed in by the user
14
     *
15
     * @return string
16 4
     */
17
    public function line()
18 4
    {
19
        return trim(fgets($this->getStdIn(), 1024));
20
    }
21
22
    /**
23
     * Read from STDIN until EOF (^D) is reached
24
     *
25
     * @return string
26 4
     */
27
    public function multiLine()
28 4
    {
29
        return trim(stream_get_contents($this->getStdIn()));
30
    }
31
32
    /**
33
     * Read one character
34
     *
35
     * @param int $count
36
     *
37
     * @return string
38 4
     */
39
    public function char($count = 1)
40 4
    {
41
        return fread($this->getStdIn(), $count);
42
    }
43
44
    /**
45
     * Read the line, but hide what the user is typing
46
     *
47
     * @return string
48
     */
49
    public function hidden()
50
    {
51
        return CliPrompt::hiddenPrompt();
52
    }
53
54
    /**
55
     * Return a valid STDIN, even if it previously EOF'ed
56
     *
57
     * Lazily re-opens STDIN after hitting an EOF
58
     *
59
     * @return resource
60
     * @throws RuntimeException
61 12
     */
62
    protected function getStdIn()
63 12
    {
64
        if ($this->stdIn && !feof($this->stdIn)) {
65
            return $this->stdIn;
66
        }
67
68 12
        try {
69 12
            $this->setStdIn();
70
        } catch (\Error $e) {
71
            throw new RuntimeException('Unable to read from STDIN', 0, $e);
72
        }
73 12
74
        return $this->stdIn;
75
    }
76
77
    /**
78
     * Attempt to set the stdin property
79
     *
80
     * @return void
81 12
     * @throws RuntimeException
82
     */
83 12
    protected function setStdIn()
84
    {
85
        if ($this->stdIn !== false) {
86
            fclose($this->stdIn);
87 12
        }
88
89 12
        $this->stdIn = fopen('php://stdin', 'r');
90
91
        if (!$this->stdIn) {
92 12
            throw new RuntimeException('Unable to read from STDIN');
93
        }
94
    }
95
}
96