Completed
Pull Request — master (#148)
by Alejandro
03:40
created

AbstractCreateShortCodeAction   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 100
Duplicated Lines 11 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 11
loc 100
rs 10
wmc 6
lcom 1
cbo 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 11 11 1
B handle() 0 60 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 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
        parent::__construct($logger);
42
        $this->urlShortener = $urlShortener;
43
        $this->translator = $translator;
44
        $this->domainConfig = $domainConfig;
45
    }
46
47
    /**
48
     * @param Request $request
49
     * @return Response
50
     * @throws \InvalidArgumentException
51
     */
52
    public function handle(Request $request): Response
53
    {
54
        try {
55
            $shortCodeData = $this->buildUrlToShortCodeData($request);
56
            $shortCodeMeta = $shortCodeData->getMeta();
57
            $longUrl = $shortCodeData->getLongUrl();
58
            $customSlug = $shortCodeMeta->getCustomSlug();
59
        } catch (InvalidArgumentException $e) {
60
            $this->logger->warning('Provided data is invalid.' . PHP_EOL . $e);
61
            return new JsonResponse([
62
                'error' => RestUtils::INVALID_ARGUMENT_ERROR,
63
                'message' => $e->getMessage(),
64
            ], self::STATUS_BAD_REQUEST);
65
        }
66
67
        try {
68
            $shortCode = $this->urlShortener->urlToShortCode(
69
                $longUrl,
70
                $shortCodeData->getTags(),
71
                $shortCodeMeta->getValidSince(),
72
                $shortCodeMeta->getValidUntil(),
73
                $customSlug,
74
                $shortCodeMeta->getMaxVisits()
75
            );
76
            $shortUrl = (new Uri())->withPath($shortCode)
77
                                   ->withScheme($this->domainConfig['schema'])
78
                                   ->withHost($this->domainConfig['hostname']);
79
80
            // TODO Make response to be generated based on Accept header
81
            return new JsonResponse([
82
                'longUrl' => (string) $longUrl,
83
                'shortUrl' => (string) $shortUrl,
84
                'shortCode' => $shortCode,
85
            ]);
86
        } catch (InvalidUrlException $e) {
87
            $this->logger->warning('Provided Invalid URL.' . PHP_EOL . $e);
88
            return new JsonResponse([
89
                'error' => RestUtils::getRestErrorCodeFromException($e),
90
                'message' => \sprintf(
91
                    $this->translator->translate('Provided URL %s is invalid. Try with a different one.'),
92
                    $longUrl
93
                ),
94
            ], self::STATUS_BAD_REQUEST);
95
        } catch (NonUniqueSlugException $e) {
96
            $this->logger->warning('Provided non-unique slug.' . PHP_EOL . $e);
97
            return new JsonResponse([
98
                'error' => RestUtils::getRestErrorCodeFromException($e),
99
                'message' => \sprintf(
100
                    $this->translator->translate('Provided slug %s is already in use. Try with a different one.'),
101
                    $customSlug
102
                ),
103
            ], self::STATUS_BAD_REQUEST);
104
        } catch (\Throwable $e) {
105
            $this->logger->error('Unexpected error creating shortcode.' . PHP_EOL . $e);
106
            return new JsonResponse([
107
                'error' => RestUtils::UNKNOWN_ERROR,
108
                'message' => $this->translator->translate('Unexpected error occurred'),
109
            ], self::STATUS_INTERNAL_SERVER_ERROR);
110
        }
111
    }
112
113
    /**
114
     * @param Request $request
115
     * @return CreateShortCodeData
116
     * @throws InvalidArgumentException
117
     */
118
    abstract protected function buildUrlToShortCodeData(Request $request): CreateShortCodeData;
119
}
120