Passed
Pull Request — master (#500)
by Alejandro
06:23
created

GenerateShortUrlCommand::execute()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 40
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 5.2

Importance

Changes 0
Metric Value
cc 5
eloc 30
c 0
b 0
f 0
nc 6
nop 2
dl 0
loc 40
ccs 24
cts 30
cp 0.8
crap 5.2
rs 9.1288
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\CLI\Command\ShortUrl;
5
6
use Cake\Chronos\Chronos;
7
use Shlinkio\Shlink\CLI\Util\ExitCodes;
8
use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
9
use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException;
10
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
11
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
12
use Symfony\Component\Console\Command\Command;
13
use Symfony\Component\Console\Input\InputArgument;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Input\InputOption;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Console\Style\SymfonyStyle;
18
use Zend\Diactoros\Uri;
19
20
use function array_map;
21
use function Functional\curry;
22
use function Functional\flatten;
23
use function Functional\unique;
24
use function sprintf;
25
26
class GenerateShortUrlCommand extends Command
27
{
28
    public const NAME = 'short-url:generate';
29
    private const ALIASES = ['shortcode:generate', 'short-code:generate'];
30
31
    /** @var UrlShortenerInterface */
32
    private $urlShortener;
33
    /** @var array */
34
    private $domainConfig;
35
36 3
    public function __construct(UrlShortenerInterface $urlShortener, array $domainConfig)
37
    {
38 3
        parent::__construct();
39 3
        $this->urlShortener = $urlShortener;
40 3
        $this->domainConfig = $domainConfig;
41
    }
42
43 3
    protected function configure(): void
44
    {
45
        $this
46 3
            ->setName(self::NAME)
47 3
            ->setAliases(self::ALIASES)
48 3
            ->setDescription('Generates a short URL for provided long URL and returns it')
49 3
            ->addArgument('longUrl', InputArgument::REQUIRED, 'The long URL to parse')
50 3
            ->addOption(
51 3
                'tags',
52 3
                't',
53 3
                InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
54 3
                'Tags to apply to the new short URL'
55
            )
56 3
            ->addOption(
57 3
                'validSince',
58 3
                's',
59 3
                InputOption::VALUE_REQUIRED,
60
                'The date from which this short URL will be valid. '
61 3
                . 'If someone tries to access it before this date, it will not be found.'
62
            )
63 3
            ->addOption(
64 3
                'validUntil',
65 3
                'u',
66 3
                InputOption::VALUE_REQUIRED,
67
                'The date until which this short URL will be valid. '
68 3
                . 'If someone tries to access it after this date, it will not be found.'
69
            )
70 3
            ->addOption(
71 3
                'customSlug',
72 3
                'c',
73 3
                InputOption::VALUE_REQUIRED,
74 3
                'If provided, this slug will be used instead of generating a short code'
75
            )
76 3
            ->addOption(
77 3
                'maxVisits',
78 3
                'm',
79 3
                InputOption::VALUE_REQUIRED,
80 3
                'This will limit the number of visits for this short URL.'
81
            )
82 3
            ->addOption(
83 3
                'findIfExists',
84 3
                'f',
85 3
                InputOption::VALUE_NONE,
86 3
                'This will force existing matching URL to be returned if found, instead of creating a new one.'
87
            );
88
    }
89
90 3
    protected function interact(InputInterface $input, OutputInterface $output): void
91
    {
92 3
        $io = new SymfonyStyle($input, $output);
93 3
        $longUrl = $input->getArgument('longUrl');
94 3
        if (! empty($longUrl)) {
95 3
            return;
96
        }
97
98
        $longUrl = $io->ask('A long URL was not provided. Which URL do you want to be shortened?');
99
        if (! empty($longUrl)) {
100
            $input->setArgument('longUrl', $longUrl);
101
        }
102
    }
103
104 3
    protected function execute(InputInterface $input, OutputInterface $output): ?int
105
    {
106 3
        $io = new SymfonyStyle($input, $output);
107 3
        $longUrl = $input->getArgument('longUrl');
108 3
        if (empty($longUrl)) {
109
            $io->error('A URL was not provided!');
110
            return ExitCodes::EXIT_FAILURE;
111
        }
112
113 3
        $explodeWithComma = curry('explode')(',');
114 3
        $tags = unique(flatten(array_map($explodeWithComma, $input->getOption('tags'))));
0 ignored issues
show
Bug introduced by
It seems like $input->getOption('tags') can also be of type boolean and null and string; however, parameter $arr1 of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

114
        $tags = unique(flatten(array_map($explodeWithComma, /** @scrutinizer ignore-type */ $input->getOption('tags'))));
Loading history...
115 3
        $customSlug = $input->getOption('customSlug');
116 3
        $maxVisits = $input->getOption('maxVisits');
117
118
        try {
119 3
            $shortUrl = $this->urlShortener->urlToShortCode(
120 3
                new Uri($longUrl),
0 ignored issues
show
Bug introduced by
It seems like $longUrl can also be of type string[]; however, parameter $uri of Zend\Diactoros\Uri::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

120
                new Uri(/** @scrutinizer ignore-type */ $longUrl),
Loading history...
121 3
                $tags,
122 3
                ShortUrlMeta::createFromParams(
123 3
                    $this->getOptionalDate($input, 'validSince'),
124 3
                    $this->getOptionalDate($input, 'validUntil'),
125 3
                    $customSlug,
0 ignored issues
show
Bug introduced by
It seems like $customSlug can also be of type string[]; however, parameter $customSlug of Shlinkio\Shlink\Core\Mod...eta::createFromParams() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

125
                    /** @scrutinizer ignore-type */ $customSlug,
Loading history...
126 3
                    $maxVisits !== null ? (int) $maxVisits : null,
127 3
                    $input->getOption('findIfExists')
128
                )
129
            );
130
131 2
            $io->writeln([
132 2
                sprintf('Processed long URL: <info>%s</info>', $longUrl),
0 ignored issues
show
Bug introduced by
It seems like $longUrl can also be of type string[]; however, parameter $args of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

132
                sprintf('Processed long URL: <info>%s</info>', /** @scrutinizer ignore-type */ $longUrl),
Loading history...
133 2
                sprintf('Generated short URL: <info>%s</info>', $shortUrl->toString($this->domainConfig)),
134
            ]);
135 2
            return ExitCodes::EXIT_SUCCESS;
136 1
        } catch (InvalidUrlException $e) {
137 1
            $io->error(sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl));
138 1
            return ExitCodes::EXIT_FAILURE;
139
        } catch (NonUniqueSlugException $e) {
140
            $io->error(
141
                sprintf('Provided slug "%s" is already in use by another URL. Try with a different one.', $customSlug)
142
            );
143
            return ExitCodes::EXIT_FAILURE;
144
        }
145
    }
146
147 3
    private function getOptionalDate(InputInterface $input, string $fieldName): ?Chronos
148
    {
149 3
        $since = $input->getOption($fieldName);
150 3
        return $since !== null ? Chronos::parse($since) : null;
0 ignored issues
show
Bug introduced by
It seems like $since can also be of type string[]; however, parameter $time of Cake\Chronos\Chronos::parse() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

150
        return $since !== null ? Chronos::parse(/** @scrutinizer ignore-type */ $since) : null;
Loading history...
151
    }
152
}
153