Completed
Pull Request — master (#194)
by Alejandro
03:44
created

GenerateShortcodeCommand::execute()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 6.478

Importance

Changes 0
Metric Value
cc 6
nc 15
nop 2
dl 0
loc 50
ccs 29
cts 38
cp 0.7632
crap 6.478
rs 8.4686
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\CLI\Command\Shortcode;
5
6
use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
7
use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException;
8
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
9
use Symfony\Component\Console\Command\Command;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Input\InputOption;
13
use Symfony\Component\Console\Output\OutputInterface;
14
use Symfony\Component\Console\Style\SymfonyStyle;
15
use Zend\Diactoros\Uri;
16
use Zend\I18n\Translator\TranslatorInterface;
17
18
class GenerateShortcodeCommand extends Command
19
{
20
    const NAME = 'shortcode:generate';
21
22
    /**
23
     * @var UrlShortenerInterface
24
     */
25
    private $urlShortener;
26
    /**
27
     * @var array
28
     */
29
    private $domainConfig;
30
    /**
31
     * @var TranslatorInterface
32
     */
33
    private $translator;
34
35 2
    public function __construct(
36
        UrlShortenerInterface $urlShortener,
37
        TranslatorInterface $translator,
38
        array $domainConfig
39
    ) {
40 2
        $this->urlShortener = $urlShortener;
41 2
        $this->translator = $translator;
42 2
        $this->domainConfig = $domainConfig;
43 2
        parent::__construct(null);
44 2
    }
45
46 2
    public function configure()
47
    {
48 2
        $this->setName(self::NAME)
49 2
             ->setDescription(
50 2
                 $this->translator->translate('Generates a short code for provided URL and returns the short URL')
51
             )
52 2
             ->addArgument('longUrl', InputArgument::REQUIRED, $this->translator->translate('The long URL to parse'))
53 2
             ->addOption(
54 2
                 'tags',
55 2
                 't',
56 2
                 InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
57 2
                 $this->translator->translate('Tags to apply to the new short URL')
58
             )
59 2
             ->addOption('validSince', 's', InputOption::VALUE_REQUIRED, $this->translator->translate(
60
                 'The date from which this short URL will be valid. '
61 2
                 . 'If someone tries to access it before this date, it will not be found.'
62
             ))
63 2
             ->addOption('validUntil', 'u', InputOption::VALUE_REQUIRED, $this->translator->translate(
64
                 'The date until which this short URL will be valid. '
65 2
                 . 'If someone tries to access it after this date, it will not be found.'
66
             ))
67 2
             ->addOption('customSlug', 'c', InputOption::VALUE_REQUIRED, $this->translator->translate(
68 2
                 'If provided, this slug will be used instead of generating a short code'
69
             ))
70 2
             ->addOption('maxVisits', 'm', InputOption::VALUE_REQUIRED, $this->translator->translate(
71 2
                 'This will limit the number of visits for this short URL.'
72
             ));
73 2
    }
74
75 2 View Code Duplication
    public function interact(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
    {
77 2
        $io = new SymfonyStyle($input, $output);
78 2
        $longUrl = $input->getArgument('longUrl');
79 2
        if (! empty($longUrl)) {
80 2
            return;
81
        }
82
83
        $longUrl = $io->ask(
84
            $this->translator->translate('A long URL was not provided. Which URL do you want to be shortened?')
85
        );
86
        if (! empty($longUrl)) {
87
            $input->setArgument('longUrl', $longUrl);
88
        }
89
    }
90
91 2
    public function execute(InputInterface $input, OutputInterface $output)
92
    {
93 2
        $io = new SymfonyStyle($input, $output);
94 2
        $longUrl = $input->getArgument('longUrl');
95 2
        if (empty($longUrl)) {
96
            $io->error($this->translator->translate('A URL was not provided!'));
97
            return;
98
        }
99
100 2
        $tags = $input->getOption('tags');
101 2
        $processedTags = [];
102 2
        foreach ($tags as $key => $tag) {
103
            $explodedTags = \explode(',', $tag);
104
            $processedTags = \array_merge($processedTags, $explodedTags);
105
        }
106 2
        $tags = $processedTags;
107 2
        $customSlug = $input->getOption('customSlug');
108 2
        $maxVisits = $input->getOption('maxVisits');
109
110
        try {
111 2
            $shortCode = $this->urlShortener->urlToShortCode(
112 2
                new Uri($longUrl),
113 2
                $tags,
114 2
                $this->getOptionalDate($input, 'validSince'),
115 2
                $this->getOptionalDate($input, 'validUntil'),
116 2
                $customSlug,
117 2
                $maxVisits !== null ? (int) $maxVisits : null
118 1
            )->getShortCode();
119 1
            $shortUrl = (string) (new Uri())->withPath($shortCode)
120 1
                                            ->withScheme($this->domainConfig['schema'])
121 1
                                            ->withHost($this->domainConfig['hostname']);
122
123 1
            $io->writeln([
124 1
                \sprintf('%s <info>%s</info>', $this->translator->translate('Processed long URL:'), $longUrl),
125 1
                \sprintf('%s <info>%s</info>', $this->translator->translate('Generated short URL:'), $shortUrl),
126
            ]);
127 1
        } catch (InvalidUrlException $e) {
128 1
            $io->error(\sprintf(
129 1
                $this->translator->translate('Provided URL "%s" is invalid. Try with a different one.'),
130 1
                $longUrl
131
            ));
132
        } catch (NonUniqueSlugException $e) {
133
            $io->error(\sprintf(
134
                $this->translator->translate(
135
                    'Provided slug "%s" is already in use by another URL. Try with a different one.'
136
                ),
137
                $customSlug
138
            ));
139
        }
140 2
    }
141
142 2
    private function getOptionalDate(InputInterface $input, string $fieldName)
143
    {
144 2
        $since = $input->getOption($fieldName);
145 2
        return $since !== null ? new \DateTime($since) : null;
146
    }
147
}
148