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

GenerateShortUrlCommand::execute()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 41
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 5.1647

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 41
ccs 26
cts 32
cp 0.8125
rs 9.0968
c 0
b 0
f 0
cc 5
nc 8
nop 2
crap 5.1647
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 Shlinkio\Shlink\Core\Util\ShortUrlBuilderTrait;
13
use Symfony\Component\Console\Command\Command;
14
use Symfony\Component\Console\Input\InputArgument;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Input\InputOption;
17
use Symfony\Component\Console\Output\OutputInterface;
18
use Symfony\Component\Console\Style\SymfonyStyle;
19
use Zend\Diactoros\Uri;
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
    use ShortUrlBuilderTrait;
29
30
    public const NAME = 'short-url:generate';
31
    private const ALIASES = ['shortcode:generate', 'short-code:generate'];
32
33
    /** @var UrlShortenerInterface */
34
    private $urlShortener;
35
    /** @var array */
36
    private $domainConfig;
37
38 3
    public function __construct(UrlShortenerInterface $urlShortener, array $domainConfig)
39
    {
40 3
        parent::__construct();
41 3
        $this->urlShortener = $urlShortener;
42 3
        $this->domainConfig = $domainConfig;
43
    }
44
45 3
    protected function configure(): void
46
    {
47
        $this
48 3
            ->setName(self::NAME)
49 3
            ->setAliases(self::ALIASES)
50 3
            ->setDescription('Generates a short URL for provided long URL and returns it')
51 3
            ->addArgument('longUrl', InputArgument::REQUIRED, 'The long URL to parse')
52 3
            ->addOption(
53 3
                'tags',
54 3
                't',
55 3
                InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
56 3
                'Tags to apply to the new short URL'
57
            )
58 3
            ->addOption(
59 3
                'validSince',
60 3
                's',
61 3
                InputOption::VALUE_REQUIRED,
62
                'The date from which this short URL will be valid. '
63 3
                . 'If someone tries to access it before this date, it will not be found.'
64
            )
65 3
            ->addOption(
66 3
                'validUntil',
67 3
                'u',
68 3
                InputOption::VALUE_REQUIRED,
69
                'The date until which this short URL will be valid. '
70 3
                . 'If someone tries to access it after this date, it will not be found.'
71
            )
72 3
            ->addOption(
73 3
                'customSlug',
74 3
                'c',
75 3
                InputOption::VALUE_REQUIRED,
76 3
                'If provided, this slug will be used instead of generating a short code'
77
            )
78 3
            ->addOption(
79 3
                'maxVisits',
80 3
                'm',
81 3
                InputOption::VALUE_REQUIRED,
82 3
                'This will limit the number of visits for this short URL.'
83
            )
84 3
            ->addOption(
85 3
                'findIfExists',
86 3
                'f',
87 3
                InputOption::VALUE_NONE,
88 3
                'This will force existing matching URL to be returned if found, instead of creating a new one.'
89
            );
90
    }
91
92 3
    protected function interact(InputInterface $input, OutputInterface $output): void
93
    {
94 3
        $io = new SymfonyStyle($input, $output);
95 3
        $longUrl = $input->getArgument('longUrl');
96 3
        if (! empty($longUrl)) {
97 3
            return;
98
        }
99
100
        $longUrl = $io->ask('A long URL was not provided. Which URL do you want to be shortened?');
101
        if (! empty($longUrl)) {
102
            $input->setArgument('longUrl', $longUrl);
103
        }
104
    }
105
106 3
    protected function execute(InputInterface $input, OutputInterface $output): ?int
107
    {
108 3
        $io = new SymfonyStyle($input, $output);
109 3
        $longUrl = $input->getArgument('longUrl');
110 3
        if (empty($longUrl)) {
111
            $io->error('A URL was not provided!');
112
            return ExitCodes::EXIT_FAILURE;
113
        }
114
115 3
        $explodeWithComma = curry('explode')(',');
116 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

116
        $tags = unique(flatten(array_map($explodeWithComma, /** @scrutinizer ignore-type */ $input->getOption('tags'))));
Loading history...
117 3
        $customSlug = $input->getOption('customSlug');
118 3
        $maxVisits = $input->getOption('maxVisits');
119
120
        try {
121 3
            $shortCode = $this->urlShortener->urlToShortCode(
122 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

122
                new Uri(/** @scrutinizer ignore-type */ $longUrl),
Loading history...
123 3
                $tags,
124 3
                ShortUrlMeta::createFromParams(
125 3
                    $this->getOptionalDate($input, 'validSince'),
126 3
                    $this->getOptionalDate($input, 'validUntil'),
127 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

127
                    /** @scrutinizer ignore-type */ $customSlug,
Loading history...
128 3
                    $maxVisits !== null ? (int) $maxVisits : null,
129 3
                    $input->getOption('findIfExists')
130
                )
131 2
            )->getShortCode();
132 2
            $shortUrl = $this->buildShortUrl($this->domainConfig, $shortCode);
133
134 2
            $io->writeln([
135 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

135
                sprintf('Processed long URL: <info>%s</info>', /** @scrutinizer ignore-type */ $longUrl),
Loading history...
136 2
                sprintf('Generated short URL: <info>%s</info>', $shortUrl),
137
            ]);
138 2
            return ExitCodes::EXIT_SUCCESS;
139 1
        } catch (InvalidUrlException $e) {
140 1
            $io->error(sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl));
141 1
            return ExitCodes::EXIT_FAILURE;
142
        } catch (NonUniqueSlugException $e) {
143
            $io->error(
144
                sprintf('Provided slug "%s" is already in use by another URL. Try with a different one.', $customSlug)
145
            );
146
            return ExitCodes::EXIT_FAILURE;
147
        }
148
    }
149
150 3
    private function getOptionalDate(InputInterface $input, string $fieldName): ?Chronos
151
    {
152 3
        $since = $input->getOption($fieldName);
153 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

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