Passed
Pull Request — master (#503)
by Alejandro
07:20
created

GenerateShortUrlCommand::interact()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.4746

Importance

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

121
        $tags = unique(flatten(array_map($explodeWithComma, /** @scrutinizer ignore-type */ $input->getOption('tags'))));
Loading history...
122 4
        $customSlug = $input->getOption('customSlug');
123 4
        $maxVisits = $input->getOption('maxVisits');
124
125
        try {
126 4
            $shortUrl = $this->urlShortener->urlToShortCode(
127 4
                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

127
                new Uri(/** @scrutinizer ignore-type */ $longUrl),
Loading history...
128
                $tags,
129 4
                ShortUrlMeta::createFromParams(
130 4
                    $this->getOptionalDate($input, 'validSince'),
131 4
                    $this->getOptionalDate($input, 'validUntil'),
132 4
                    $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

132
                    /** @scrutinizer ignore-type */ $customSlug,
Loading history...
133 4
                    $maxVisits !== null ? (int) $maxVisits : null,
134 4
                    $input->getOption('findIfExists'),
135 4
                    $input->getOption('domain')
136
                )
137
            );
138
139 2
            $io->writeln([
140 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

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

158
        return $since !== null ? Chronos::parse(/** @scrutinizer ignore-type */ $since) : null;
Loading history...
159
    }
160
}
161