Completed
Pull Request — master (#224)
by Alejandro
03:34
created

UrlShortenerConfigCustomizer::ask()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 6
nop 2
dl 0
loc 21
rs 8.9617
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Installer\Config\Plugin;
5
6
use Shlinkio\Shlink\Core\Service\UrlShortener;
7
use Shlinkio\Shlink\Installer\Model\CustomizableAppConfig;
8
use Shlinkio\Shlink\Installer\Util\AskUtilsTrait;
9
use Symfony\Component\Console\Style\SymfonyStyle;
10
use function array_diff;
11
use function array_keys;
12
use function str_shuffle;
13
14
class UrlShortenerConfigCustomizer implements ConfigCustomizerInterface
15
{
16
    use AskUtilsTrait;
17
18
    private const SCHEMA = 'SCHEMA';
19
    private const HOSTNAME = 'HOSTNAME';
20
    private const CHARS = 'CHARS';
21
    private const VALIDATE_URL = 'VALIDATE_URL';
22
    private const EXPECTED_KEYS = [
23
        self::SCHEMA,
24
        self::HOSTNAME,
25
        self::CHARS,
26
        self::VALIDATE_URL,
27
    ];
28
29
    public function process(SymfonyStyle $io, CustomizableAppConfig $appConfig): void
30
    {
31
        $io->title('URL SHORTENER');
32
33
        $urlShortener = $appConfig->getUrlShortener();
34
        $doImport = $appConfig->hasUrlShortener() && $io->confirm('Do you want to keep imported URL shortener config?');
35
        $keysToAskFor = $doImport ? array_diff(self::EXPECTED_KEYS, array_keys($urlShortener)) : self::EXPECTED_KEYS;
36
37
        if (empty($keysToAskFor)) {
38
            return;
39
        }
40
41
        foreach ($keysToAskFor as $key) {
42
            $urlShortener[$key] = $this->ask($io, $key);
43
        }
44
        $appConfig->setUrlShortener($urlShortener);
45
    }
46
47
    private function ask(SymfonyStyle $io, string $key)
48
    {
49
        switch ($key) {
50
            case self::SCHEMA:
51
                return $io->choice(
52
                    'Select schema for generated short URLs',
53
                    ['http', 'https'],
54
                    'http'
55
                );
56
            case self::HOSTNAME:
57
                return $this->askRequired($io, 'hostname', 'Hostname for generated URLs');
58
            case self::CHARS:
59
                return $io->ask(
60
                    'Character set for generated short codes (leave empty to autogenerate one)'
61
                ) ?: str_shuffle(UrlShortener::DEFAULT_CHARS);
62
            case self::VALIDATE_URL:
63
                return $io->confirm('Do you want to validate long urls by 200 HTTP status code on response');
64
        }
65
66
        return '';
67
    }
68
}
69