Completed
Pull Request — master (#148)
by Alejandro
04:08
created

AbstractCreateShortCodeAction   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 99
Duplicated Lines 11.11 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 11
loc 99
ccs 53
cts 53
cp 1
rs 10
wmc 6
lcom 1
cbo 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 11 11 1
B handle() 0 59 5
buildUrlToShortCodeData() 0 1 ?

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Action\ShortCode;
5
6
use Psr\Http\Message\ResponseInterface as Response;
7
use Psr\Http\Message\ServerRequestInterface as Request;
8
use Psr\Log\LoggerInterface;
9
use Shlinkio\Shlink\Core\Exception\InvalidArgumentException;
10
use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
11
use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException;
12
use Shlinkio\Shlink\Core\Model\CreateShortCodeData;
13
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
14
use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
15
use Shlinkio\Shlink\Rest\Util\RestUtils;
16
use Zend\Diactoros\Response\JsonResponse;
17
use Zend\Diactoros\Uri;
18
use Zend\I18n\Translator\TranslatorInterface;
19
20
abstract class AbstractCreateShortCodeAction extends AbstractRestAction
21
{
22
    /**
23
     * @var UrlShortenerInterface
24
     */
25
    private $urlShortener;
26
    /**
27
     * @var array
28
     */
29
    private $domainConfig;
30
    /**
31
     * @var TranslatorInterface
32
     */
33
    protected $translator;
34
35 9 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...
36
        UrlShortenerInterface $urlShortener,
37
        TranslatorInterface $translator,
38
        array $domainConfig,
39
        LoggerInterface $logger = null
40
    ) {
41 9
        parent::__construct($logger);
42 9
        $this->urlShortener = $urlShortener;
43 9
        $this->translator = $translator;
44 9
        $this->domainConfig = $domainConfig;
45 9
    }
46
47
    /**
48
     * @param Request $request
49
     * @return Response
50
     * @throws \InvalidArgumentException
51
     */
52 9
    public function handle(Request $request): Response
53
    {
54
        try {
55 9
            $shortCodeData = $this->buildUrlToShortCodeData($request);
56 5
            $shortCodeMeta = $shortCodeData->getMeta();
57 5
            $longUrl = $shortCodeData->getLongUrl();
58 5
            $customSlug = $shortCodeMeta->getCustomSlug();
59 4
        } catch (InvalidArgumentException $e) {
60 4
            $this->logger->warning('Provided data is invalid.' . PHP_EOL . $e);
61 4
            return new JsonResponse([
62 4
                'error' => RestUtils::INVALID_ARGUMENT_ERROR,
63 4
                'message' => $e->getMessage(),
64 4
            ], self::STATUS_BAD_REQUEST);
65
        }
66
67
        try {
68 5
            $shortCode = $this->urlShortener->urlToShortCode(
69 5
                $longUrl,
70 5
                $shortCodeData->getTags(),
71 5
                $shortCodeMeta->getValidSince(),
72 5
                $shortCodeMeta->getValidUntil(),
73 5
                $customSlug,
74 5
                $shortCodeMeta->getMaxVisits()
75
            );
76 2
            $shortUrl = (new Uri())->withPath($shortCode)
77 2
                                   ->withScheme($this->domainConfig['schema'])
78 2
                                   ->withHost($this->domainConfig['hostname']);
79
80 2
            return new JsonResponse([
81 2
                'longUrl' => (string) $longUrl,
82 2
                'shortUrl' => (string) $shortUrl,
83 2
                'shortCode' => $shortCode,
84
            ]);
85 3
        } catch (InvalidUrlException $e) {
86 1
            $this->logger->warning('Provided Invalid URL.' . PHP_EOL . $e);
87 1
            return new JsonResponse([
88 1
                'error' => RestUtils::getRestErrorCodeFromException($e),
89 1
                'message' => \sprintf(
90 1
                    $this->translator->translate('Provided URL %s is invalid. Try with a different one.'),
91 1
                    $longUrl
92
                ),
93 1
            ], self::STATUS_BAD_REQUEST);
94 2
        } catch (NonUniqueSlugException $e) {
95 1
            $this->logger->warning('Provided non-unique slug.' . PHP_EOL . $e);
96 1
            return new JsonResponse([
97 1
                'error' => RestUtils::getRestErrorCodeFromException($e),
98 1
                'message' => \sprintf(
99 1
                    $this->translator->translate('Provided slug %s is already in use. Try with a different one.'),
100 1
                    $customSlug
101
                ),
102 1
            ], self::STATUS_BAD_REQUEST);
103 1
        } catch (\Throwable $e) {
104 1
            $this->logger->error('Unexpected error creating shortcode.' . PHP_EOL . $e);
105 1
            return new JsonResponse([
106 1
                'error' => RestUtils::UNKNOWN_ERROR,
107 1
                'message' => $this->translator->translate('Unexpected error occurred'),
108 1
            ], self::STATUS_INTERNAL_SERVER_ERROR);
109
        }
110
    }
111
112
    /**
113
     * @param Request $request
114
     * @return CreateShortCodeData
115
     * @throws InvalidArgumentException
116
     */
117
    abstract protected function buildUrlToShortCodeData(Request $request): CreateShortCodeData;
118
}
119