Completed
Push — master ( bc61b5...79c132 )
by Alejandro
26s queued 11s
created

GenerateShortUrlCommand::execute()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 37
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 5.1281

Importance

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

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

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

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

134
                sprintf('Processed long URL: <info>%s</info>', /** @scrutinizer ignore-type */ $longUrl),
Loading history...
135 2
                sprintf('Generated short URL: <info>%s</info>', $shortUrl),
136
            ]);
137 1
        } catch (InvalidUrlException $e) {
138 1
            $io->error(sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl));
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
        }
144
    }
145
146 3
    private function getOptionalDate(InputInterface $input, string $fieldName): ?Chronos
147
    {
148 3
        $since = $input->getOption($fieldName);
149 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

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