Completed
Push — master ( f60c21...243075 )
by Alejandro
10:43
created

CreateShortcodeAction::process()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 56
Code Lines 46

Duplication

Lines 6
Ratio 10.71 %

Code Coverage

Tests 45
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 46
nc 11
nop 2
dl 6
loc 56
rs 8.7592
c 0
b 0
f 0
ccs 45
cts 45
cp 1
crap 6

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\Rest\Action;
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\InvalidUrlException;
10
use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException;
11
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
12
use Shlinkio\Shlink\Rest\Util\RestUtils;
13
use Zend\Diactoros\Response\JsonResponse;
14
use Zend\Diactoros\Uri;
15
use Zend\I18n\Translator\TranslatorInterface;
16
17
class CreateShortcodeAction extends AbstractRestAction
18
{
19
    /**
20
     * @var UrlShortenerInterface
21
     */
22
    private $urlShortener;
23
    /**
24
     * @var array
25
     */
26
    private $domainConfig;
27
    /**
28
     * @var TranslatorInterface
29
     */
30
    private $translator;
31
32 5 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...
33
        UrlShortenerInterface $urlShortener,
34
        TranslatorInterface $translator,
35
        array $domainConfig,
36
        LoggerInterface $logger = null
37
    ) {
38 5
        parent::__construct($logger);
39 5
        $this->urlShortener = $urlShortener;
40 5
        $this->translator = $translator;
41 5
        $this->domainConfig = $domainConfig;
42 5
    }
43
44
    /**
45
     * @param Request $request
46
     * @return Response
47
     * @throws \InvalidArgumentException
48
     */
49 5
    public function handle(Request $request): Response
50
    {
51 5
        $postData = (array) $request->getParsedBody();
52 5 View Code Duplication
        if (! isset($postData['longUrl'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
53 1
            return new JsonResponse([
54 1
                'error' => RestUtils::INVALID_ARGUMENT_ERROR,
55 1
                'message' => $this->translator->translate('A URL was not provided'),
56 1
            ], self::STATUS_BAD_REQUEST);
57
        }
58 4
        $longUrl = $postData['longUrl'];
59 4
        $customSlug = $postData['customSlug'] ?? null;
60
61
        try {
62 4
            $shortCode = $this->urlShortener->urlToShortCode(
63 4
                new Uri($longUrl),
64 4
                (array) ($postData['tags'] ?? []),
65 4
                $this->getOptionalDate($postData, 'validSince'),
66 4
                $this->getOptionalDate($postData, 'validUntil'),
67 4
                $customSlug,
68 4
                isset($postData['maxVisits']) ? (int) $postData['maxVisits'] : null
69
            );
70 1
            $shortUrl = (new Uri())->withPath($shortCode)
71 1
                                   ->withScheme($this->domainConfig['schema'])
72 1
                                   ->withHost($this->domainConfig['hostname']);
73
74 1
            return new JsonResponse([
75 1
                'longUrl' => $longUrl,
76 1
                'shortUrl' => (string) $shortUrl,
77 1
                'shortCode' => $shortCode,
78
            ]);
79 3
        } catch (InvalidUrlException $e) {
80 1
            $this->logger->warning('Provided Invalid URL.' . PHP_EOL . $e);
81 1
            return new JsonResponse([
82 1
                'error' => RestUtils::getRestErrorCodeFromException($e),
83 1
                'message' => sprintf(
84 1
                    $this->translator->translate('Provided URL %s is invalid. Try with a different one.'),
85 1
                    $longUrl
86
                ),
87 1
            ], self::STATUS_BAD_REQUEST);
88 2
        } catch (NonUniqueSlugException $e) {
89 1
            $this->logger->warning('Provided non-unique slug.' . PHP_EOL . $e);
90 1
            return new JsonResponse([
91 1
                'error' => RestUtils::getRestErrorCodeFromException($e),
92 1
                'message' => sprintf(
93 1
                    $this->translator->translate('Provided slug %s is already in use. Try with a different one.'),
94 1
                    $customSlug
95
                ),
96 1
            ], self::STATUS_BAD_REQUEST);
97 1
        } catch (\Throwable $e) {
98 1
            $this->logger->error('Unexpected error creating shortcode.' . PHP_EOL . $e);
99 1
            return new JsonResponse([
100 1
                'error' => RestUtils::UNKNOWN_ERROR,
101 1
                'message' => $this->translator->translate('Unexpected error occurred'),
102 1
            ], self::STATUS_INTERNAL_SERVER_ERROR);
103
        }
104
    }
105
106 4
    private function getOptionalDate(array $postData, string $fieldName)
107
    {
108 4
        return isset($postData[$fieldName]) ? new \DateTime($postData[$fieldName]) : null;
109
    }
110
}
111