Completed
Push — master ( aa77c9...15a70d )
by Alejandro
27s
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
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\Service\UrlShortenerInterface;
10
use Shlinkio\Shlink\Core\Util\ShortUrlBuilderTrait;
11
use Symfony\Component\Console\Command\Command;
12
use Symfony\Component\Console\Input\InputArgument;
13
use Symfony\Component\Console\Input\InputInterface;
14
use Symfony\Component\Console\Input\InputOption;
15
use Symfony\Component\Console\Output\OutputInterface;
16
use Symfony\Component\Console\Style\SymfonyStyle;
17
use Zend\Diactoros\Uri;
18
use function array_merge;
19
use function explode;
20
use function sprintf;
21
22
class GenerateShortUrlCommand extends Command
23
{
24
    use ShortUrlBuilderTrait;
25
26
    public const NAME = 'short-url:generate';
27
    private const ALIASES = ['shortcode:generate', 'short-code:generate'];
28
29
    /**
30
     * @var UrlShortenerInterface
31
     */
32
    private $urlShortener;
33
    /**
34
     * @var array
35
     */
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
    }
85
86 3
    protected function interact(InputInterface $input, OutputInterface $output): void
87
    {
88 3
        $io = new SymfonyStyle($input, $output);
89 3
        $longUrl = $input->getArgument('longUrl');
90 3
        if (! empty($longUrl)) {
91 3
            return;
92
        }
93
94
        $longUrl = $io->ask('A long URL was not provided. Which URL do you want to be shortened?');
95
        if (! empty($longUrl)) {
96
            $input->setArgument('longUrl', $longUrl);
97
        }
98
    }
99
100 3
    protected function execute(InputInterface $input, OutputInterface $output): void
101
    {
102 3
        $io = new SymfonyStyle($input, $output);
103 3
        $longUrl = $input->getArgument('longUrl');
104 3
        if (empty($longUrl)) {
105
            $io->error('A URL was not provided!');
106
            return;
107
        }
108
109 3
        $tags = $input->getOption('tags');
110 3
        $processedTags = [];
111 3
        foreach ($tags as $key => $tag) {
112 1
            $explodedTags = explode(',', $tag);
113 1
            $processedTags = array_merge($processedTags, $explodedTags);
114
        }
115 3
        $tags = $processedTags;
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
                $this->getOptionalDate($input, 'validSince'),
124 3
                $this->getOptionalDate($input, 'validUntil'),
125 3
                $customSlug,
126 3
                $maxVisits !== null ? (int) $maxVisits : null
127 2
            )->getShortCode();
128 2
            $shortUrl = $this->buildShortUrl($this->domainConfig, $shortCode);
129
130 2
            $io->writeln([
131 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

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

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