QuestionFactory   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
dl 0
loc 27
rs 10
c 1
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A createQuestion() 0 5 2
A createChoiceQuestion() 0 12 2
1
<?php
2
3
/**
4
 * This file is part of byrokrat\giroapp.
5
 *
6
 * byrokrat\giroapp is free software: you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * byrokrat\giroapp is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with byrokrat\giroapp. If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 * Copyright 2016-21 Hannes Forsgård
20
 */
21
22
declare(strict_types=1);
23
24
namespace byrokrat\giroapp\Console\Helper;
25
26
use Symfony\Component\Console\Question\ChoiceQuestion;
27
use Symfony\Component\Console\Question\Question;
28
29
final class QuestionFactory
30
{
31
    /**
32
     * @param mixed $default
33
     */
34
    public static function createQuestion(string $question, $default = null): Question
35
    {
36
        return is_null($default)
37
            ? new Question("$question: ")
38
            : new Question("$question [<info>$default</info>]: ", $default);
39
    }
40
41
    /**
42
     * @param mixed[] $choices
43
     */
44
    public static function createChoiceQuestion(string $question, array $choices, string $default): ChoiceQuestion
45
    {
46
        $defaultKey = array_search($default, $choices);
47
48
        if (false === $defaultKey) {
49
            throw new \LogicException("Invalid default answer $default");
50
        }
51
52
        unset($choices[$defaultKey]);
53
        $choices[strtoupper((string)$defaultKey)] = $default;
54
55
        return new ChoiceQuestion("$question: ", $choices, strtoupper((string)$defaultKey));
56
    }
57
}
58