Confirm   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 60
rs 10
c 0
b 0
f 0
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setDefault() 0 4 1
A run() 0 7 2
A build() 0 14 4
A boolValidator() 0 10 3
1
<?php
2
3
namespace TheAentMachine\Prompt;
4
5
use Symfony\Component\Console\Question\Question;
6
use TheAentMachine\Prompt\Helper\ValidatorHelper;
7
8
final class Confirm extends AbstractInput
9
{
10
    /** @var null|bool */
11
    private $default;
12
13
    /**
14
     * @param null|bool $default
15
     * @return self
16
     */
17
    public function setDefault(?bool $default): self
18
    {
19
        $this->default = $default;
20
        return $this;
21
    }
22
23
    /**
24
     * @return Question
25
     */
26
    protected function build(): Question
27
    {
28
        $question = parent::build();
29
        $message = $question->getQuestion();
30
        $validator = $question->getValidator();
31
        if (!empty($this->default)) {
32
            $message .= $this->default === true ? ' [Y/n]: ' : ' [y/]: ';
33
            $question = new Question($message, $this->default === true ? 'yes' : 'no');
34
        } else {
35
            $message .= ' [y/n]: ';
36
            $question = new Question($message);
37
        }
38
        $question->setValidator(ValidatorHelper::merge($validator, $this->boolValidator()));
39
        return $question;
40
    }
41
42
    /**
43
     * @return callable|null
44
     */
45
    private function boolValidator(): ?callable
46
    {
47
        return function (?string $response) {
48
            $response = $response ?? '';
49
            $response = \strtolower(trim($response));
50
            if (!\in_array($response, ['y', 'n', 'yes', 'no'], true)) {
51
                throw new \InvalidArgumentException('Hey, answer must be "y" or "n"!');
52
            }
53
            $response = \in_array($response, ['y', 'yes'], true) ? '1' : '';
54
            return $response;
55
        };
56
    }
57
58
    /**
59
     * @return bool
60
     */
61
    public function run(): bool
62
    {
63
        $question = $this->build();
64
        do {
65
            $response = $this->questionHelper->ask($this->input, $this->output, $question);
66
        } while (!empty($this->helpText) && $response === '?');
67
        return !empty($response);
68
    }
69
}
70