Passed
Pull Request — master (#357)
by Alejandro
05:24
created

UpdateDbCommand::execute()   A

Complexity

Conditions 3
Paths 9

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3.0416

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 26
ccs 15
cts 18
cp 0.8333
rs 9.6666
c 0
b 0
f 0
cc 3
nc 9
nop 2
crap 3.0416
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\CLI\Command\Visit;
5
6
use Shlinkio\Shlink\CLI\Util\ExitCodes;
7
use Shlinkio\Shlink\Common\Exception\RuntimeException;
8
use Shlinkio\Shlink\Common\IpGeolocation\GeoLite2\DbUpdaterInterface;
9
use Symfony\Component\Console\Command\Command;
10
use Symfony\Component\Console\Helper\ProgressBar;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Symfony\Component\Console\Style\SymfonyStyle;
14
15
class UpdateDbCommand extends Command
16
{
17
    public const NAME = 'visit:update-db';
18
19
    /** @var DbUpdaterInterface */
20
    private $geoLiteDbUpdater;
21
22 2
    public function __construct(DbUpdaterInterface $geoLiteDbUpdater)
23
    {
24 2
        parent::__construct();
25 2
        $this->geoLiteDbUpdater = $geoLiteDbUpdater;
26
    }
27
28 2
    protected function configure(): void
29
    {
30
        $this
31 2
            ->setName(self::NAME)
32 2
            ->setDescription('Updates the GeoLite2 database file used to geolocate IP addresses')
33 2
            ->setHelp(
34
                'The GeoLite2 database is updated first Tuesday every month, so this command should be ideally run '
35 2
                . 'every first Wednesday'
36
            );
37
    }
38
39 2
    protected function execute(InputInterface $input, OutputInterface $output): ?int
40
    {
41 2
        $io = new SymfonyStyle($input, $output);
42 2
        $progressBar = new ProgressBar($output);
43 2
        $progressBar->start();
44
45
        try {
46
            $this->geoLiteDbUpdater->downloadFreshCopy(function (int $total, int $downloaded) use ($progressBar) {
47
                $progressBar->setMaxSteps($total);
48
                $progressBar->setProgress($downloaded);
49 2
            });
50
51 1
            $progressBar->finish();
52 1
            $io->writeln('');
53
54 1
            $io->success('GeoLite2 database properly updated');
55 1
            return ExitCodes::EXIT_SUCCESS;
56 1
        } catch (RuntimeException $e) {
57 1
            $progressBar->finish();
58 1
            $io->writeln('');
59
60 1
            $io->error('An error occurred while updating GeoLite2 database');
61 1
            if ($io->isVerbose()) {
62
                $this->getApplication()->renderException($e, $output);
63
            }
64 1
            return ExitCodes::EXIT_FAILURE;
65
        }
66
    }
67
}
68