|
1
|
|
|
<?php |
|
2
|
|
|
namespace Dbtlr\PHPEnvBuilder; |
|
3
|
|
|
|
|
4
|
|
|
use Dbtlr\PHPEnvBuilder\Exception\AskException; |
|
5
|
|
|
use Dbtlr\PHPEnvBuilder\IOHandler\IOHandlerInterface; |
|
6
|
|
|
|
|
7
|
|
|
class IO |
|
8
|
|
|
{ |
|
9
|
|
|
/** @var IOHandlerInterface */ |
|
10
|
|
|
protected $handler; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* IO constructor. |
|
14
|
|
|
* |
|
15
|
|
|
* @param IOHandlerInterface $handler |
|
16
|
|
|
*/ |
|
17
|
|
|
public function __construct(IOHandlerInterface $handler) |
|
18
|
|
|
{ |
|
19
|
|
|
$this->setHandler($handler); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Override the IO Handler. |
|
24
|
|
|
* |
|
25
|
|
|
* @param IOHandlerInterface $handler |
|
26
|
|
|
*/ |
|
27
|
|
|
public function setHandler(IOHandlerInterface $handler) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->handler = $handler; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Ask a question. |
|
34
|
|
|
* |
|
35
|
|
|
* @throws AskException |
|
36
|
|
|
* @param string $name |
|
37
|
|
|
* @param string $question |
|
38
|
|
|
* @param string $default |
|
39
|
|
|
* @param bool $required |
|
40
|
|
|
* @return string |
|
41
|
|
|
*/ |
|
42
|
|
|
public function ask(string $name, string $question, string $default = '', bool $required = false) |
|
43
|
|
|
{ |
|
44
|
|
|
$count = 0; |
|
45
|
|
|
$maxAsks = 3; |
|
46
|
|
|
|
|
47
|
|
|
while ($count++ < $maxAsks) { |
|
48
|
|
|
$response = $this->in($question, $default); |
|
49
|
|
|
|
|
50
|
|
|
if (!$required || !empty($response)) { |
|
51
|
|
|
return $response; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
$this->handler->out('A response is required...'); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
throw new AskException($name, $maxAsks); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Output a message to the console. |
|
62
|
|
|
* |
|
63
|
|
|
* @param string $message |
|
64
|
|
|
*/ |
|
65
|
|
|
public function out(string $message) |
|
66
|
|
|
{ |
|
67
|
|
|
$this->handler->out($message); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Get input from the console. |
|
72
|
|
|
* |
|
73
|
|
|
* @param string $question |
|
74
|
|
|
* @param string $default |
|
75
|
|
|
* @return mixed |
|
76
|
|
|
*/ |
|
77
|
|
|
public function in(string $question, string $default = '') |
|
78
|
|
|
{ |
|
79
|
|
|
$formatted = sprintf('%s (%s):', $question, $default); |
|
80
|
|
|
|
|
81
|
|
|
return $this->handler->in($formatted, $default); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|