Completed
Push — 2.0 ( 359ae1...221cc7 )
by Rafał
51:27 queued 18:07
created

UpdateGeoIPDatabaseCommand::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Publisher Geo IP Bundle.
7
 *
8
 * Copyright 2019 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2019 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\GeoIPBundle\Command;
18
19
use RuntimeException;
20
use SWP\Component\Archiver\Archiver\GzipArchiver;
21
use Symfony\Component\Console\Command\Command;
22
use Symfony\Component\Console\Input\InputArgument;
23
use Symfony\Component\Console\Input\InputInterface;
24
use Symfony\Component\Console\Output\OutputInterface;
25
use Symfony\Component\Filesystem\Filesystem;
26
27
class UpdateGeoIPDatabaseCommand extends Command
28
{
29
    protected static $defaultName = 'swp:geoip:db:update';
30
31
    /** @var string */
32
    private $targetDir;
33
34
    /** @var string */
35
    private $databaseUrl;
36
37
    /** @var string */
38
    private $databasePath;
39
40
    /** @var Filesystem */
41
    private $filesystem;
42
43
    public function __construct(string $targetDir, string $databaseUrl, string $databasePath, Filesystem $filesystem)
44
    {
45
        $this->targetDir = $targetDir;
46
        $this->databaseUrl = $databaseUrl;
47
        $this->databasePath = $databasePath;
48
        $this->filesystem = $filesystem;
49
50
        parent::__construct();
51
    }
52
53
    protected function configure(): void
54
    {
55
        $this
56
            ->setDescription('Downloads and updates the Geo IP database.')
57
            ->addArgument(
58
                'url',
59
                InputArgument::OPTIONAL,
60
                'GeoIP2 database URL',
61
                $this->databaseUrl
62
            )
63
        ;
64
    }
65
66
    protected function execute(InputInterface $input, OutputInterface $output): void
67
    {
68
        $archiver = new GzipArchiver();
69
        $url = (string) $input->getArgument('url');
70
71
        $zipFile = $this->targetDir.'/'.basename($url);
72
73
        $this->filesystem->copy($url, $zipFile, true);
74
        $output->writeln('Database has been downloaded!');
75
76
        $isUnArchived = $archiver->unarchive($zipFile, $this->databasePath);
77
78
        if (false === $isUnArchived) {
79
            throw new RuntimeException('Failed to unarchive the database file.');
80
        }
81
82
        $this->filesystem->remove($zipFile);
83
84
        $output->writeln('Success!');
85
    }
86
}
87