Completed
Push — master ( ccb9d5...d7e68d )
by Alejandro
09:04
created

GenerateShortcodeCommand::execute()   B

Complexity

Conditions 6
Paths 20

Size

Total Lines 51
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 6.6068

Importance

Changes 0
Metric Value
cc 6
eloc 39
nc 20
nop 2
dl 0
loc 51
rs 8.6588
c 0
b 0
f 0
ccs 29
cts 39
cp 0.7436
crap 6.6068

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Helper\QuestionHelper;
11
use Symfony\Component\Console\Input\InputArgument;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputOption;
14
use Symfony\Component\Console\Output\OutputInterface;
15
use Symfony\Component\Console\Question\Question;
16
use Zend\Diactoros\Uri;
17
use Zend\I18n\Translator\TranslatorInterface;
18
19
class GenerateShortcodeCommand extends Command
20
{
21
    /**
22
     * @var UrlShortenerInterface
23
     */
24
    private $urlShortener;
25
    /**
26
     * @var array
27
     */
28
    private $domainConfig;
29
    /**
30
     * @var TranslatorInterface
31
     */
32
    private $translator;
33
34 2 View Code Duplication
    public function __construct(
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...
35
        UrlShortenerInterface $urlShortener,
36
        TranslatorInterface $translator,
37
        array $domainConfig
38
    ) {
39 2
        $this->urlShortener = $urlShortener;
40 2
        $this->translator = $translator;
41 2
        $this->domainConfig = $domainConfig;
42 2
        parent::__construct(null);
43 2
    }
44
45 2
    public function configure()
46
    {
47 2
        $this->setName('shortcode:generate')
48 2
             ->setDescription(
49 2
                 $this->translator->translate('Generates a short code for provided URL and returns the short URL')
50
             )
51 2
             ->addArgument('longUrl', InputArgument::REQUIRED, $this->translator->translate('The long URL to parse'))
52 2
             ->addOption(
53 2
                 'tags',
54 2
                 't',
55 2
                 InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
56 2
                 $this->translator->translate('Tags to apply to the new short URL')
57
             )
58 2
             ->addOption('validSince', 's', InputOption::VALUE_REQUIRED, $this->translator->translate(
59
                 'The date from which this short URL will be valid. '
60 2
                 . 'If someone tries to access it before this date, it will not be found.'
61
             ))
62 2
             ->addOption('validUntil', 'u', InputOption::VALUE_REQUIRED, $this->translator->translate(
63
                 'The date until which this short URL will be valid. '
64 2
                 . 'If someone tries to access it after this date, it will not be found.'
65
             ))
66 2
             ->addOption('customSlug', 'c', InputOption::VALUE_REQUIRED, $this->translator->translate(
67 2
                 'If provided, this slug will be used instead of generating a short code'
68
             ))
69 2
             ->addOption('maxVisits', 'm', InputOption::VALUE_REQUIRED, $this->translator->translate(
70 2
                 'This will limit the number of visits for this short URL.'
71
             ));
72 2
    }
73
74 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...
75
    {
76 2
        $longUrl = $input->getArgument('longUrl');
77 2
        if (! empty($longUrl)) {
78 2
            return;
79
        }
80
81
        /** @var QuestionHelper $helper */
82
        $helper = $this->getHelper('question');
83
        $question = new Question(sprintf(
84
            '<question>%s</question> ',
85
            $this->translator->translate('A long URL was not provided. Which URL do you want to shorten?:')
86
        ));
87
88
        $longUrl = $helper->ask($input, $output, $question);
89
        if (! empty($longUrl)) {
90
            $input->setArgument('longUrl', $longUrl);
91
        }
92
    }
93
94 2
    public function execute(InputInterface $input, OutputInterface $output)
95
    {
96 2
        $longUrl = $input->getArgument('longUrl');
97 2
        $tags = $input->getOption('tags');
98 2
        $processedTags = [];
99 2
        foreach ($tags as $key => $tag) {
100
            $explodedTags = explode(',', $tag);
101
            $processedTags = array_merge($processedTags, $explodedTags);
102
        }
103 2
        $tags = $processedTags;
104 2
        $customSlug = $input->getOption('customSlug');
105 2
        $maxVisits = $input->getOption('maxVisits');
106
107
        try {
108 2
            if (! isset($longUrl)) {
109
                $output->writeln(sprintf('<error>%s</error>', $this->translator->translate('A URL was not provided!')));
110
                return;
111
            }
112
113 2
            $shortCode = $this->urlShortener->urlToShortCode(
114 2
                new Uri($longUrl),
115 2
                $tags,
116 2
                $this->getOptionalDate($input, 'validSince'),
117 2
                $this->getOptionalDate($input, 'validUntil'),
118 2
                $customSlug,
119 2
                $maxVisits !== null ? (int) $maxVisits : null
120
            );
121 1
            $shortUrl = (new Uri())->withPath($shortCode)
122 1
                                   ->withScheme($this->domainConfig['schema'])
123 1
                                   ->withHost($this->domainConfig['hostname']);
124
125 1
            $output->writeln([
126 1
                sprintf('%s <info>%s</info>', $this->translator->translate('Processed URL:'), $longUrl),
127 1
                sprintf('%s <info>%s</info>', $this->translator->translate('Generated URL:'), $shortUrl),
128
            ]);
129 1
        } catch (InvalidUrlException $e) {
130 1
            $output->writeln(sprintf(
131 1
                '<error>' . $this->translator->translate(
132 1
                    'Provided URL "%s" is invalid. Try with a different one.'
133 1
                ) . '</error>',
134 1
                $longUrl
135
            ));
136
        } catch (NonUniqueSlugException $e) {
137
            $output->writeln(sprintf(
138
                '<error>' . $this->translator->translate(
139
                    'Provided slug "%s" is already in use by another URL. Try with a different one.'
140
                ) . '</error>',
141
                $customSlug
142
            ));
143
        }
144 2
    }
145
146 2
    private function getOptionalDate(InputInterface $input, string $fieldName)
147
    {
148 2
        $since = $input->getOption($fieldName);
149 2
        return $since !== null ? new \DateTime($since) : null;
150
    }
151
}
152