Completed
Pull Request — master (#98)
by Alejandro
06:29
created

CreateShortcodeAction::dispatch()   B

Complexity

Conditions 6
Paths 29

Size

Total Lines 40
Code Lines 32

Duplication

Lines 6
Ratio 15 %

Code Coverage

Tests 32
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 32
nc 29
nop 2
dl 6
loc 40
ccs 32
cts 32
cp 1
crap 6
rs 8.439
c 0
b 0
f 0
1
<?php
2
namespace Shlinkio\Shlink\Rest\Action;
3
4
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
5
use Interop\Http\ServerMiddleware\DelegateInterface;
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\Service\UrlShortener;
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
    /**
33
     * GenerateShortcodeMiddleware constructor.
34
     *
35
     * @param UrlShortenerInterface $urlShortener
36
     * @param TranslatorInterface $translator
37
     * @param array $domainConfig
38
     * @param LoggerInterface|null $logger
39
     *
40
     * @Inject({UrlShortener::class, "translator", "config.url_shortener.domain", "Logger_Shlink"})
41
     */
42 4 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...
43
        UrlShortenerInterface $urlShortener,
44
        TranslatorInterface $translator,
45
        array $domainConfig,
46
        LoggerInterface $logger = null
47
    ) {
48 4
        parent::__construct($logger);
49 4
        $this->urlShortener = $urlShortener;
50 4
        $this->translator = $translator;
51 4
        $this->domainConfig = $domainConfig;
52 4
    }
53
54
    /**
55
     * @param Request $request
56
     * @param DelegateInterface $delegate
57
     * @return null|Response
58
     * @throws \InvalidArgumentException
59
     */
60 4
    public function process(Request $request, DelegateInterface $delegate)
61
    {
62 4
        $postData = $request->getParsedBody();
63 4 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...
64 1
            return new JsonResponse([
65 1
                'error' => RestUtils::INVALID_ARGUMENT_ERROR,
66 1
                'message' => $this->translator->translate('A URL was not provided'),
67 1
            ], self::STATUS_BAD_REQUEST);
68
        }
69 3
        $longUrl = $postData['longUrl'];
70 3
        $tags = isset($postData['tags']) && is_array($postData['tags']) ? $postData['tags'] : [];
71
72
        try {
73 3
            $shortCode = $this->urlShortener->urlToShortCode(new Uri($longUrl), $tags);
74 1
            $shortUrl = (new Uri())->withPath($shortCode)
75 1
                                   ->withScheme($this->domainConfig['schema'])
76 1
                                   ->withHost($this->domainConfig['hostname']);
77
78 1
            return new JsonResponse([
79 1
                'longUrl' => $longUrl,
80 1
                'shortUrl' => $shortUrl->__toString(),
81 1
                'shortCode' => $shortCode,
82
            ]);
83 2
        } catch (InvalidUrlException $e) {
84 1
            $this->logger->warning('Provided Invalid URL.' . PHP_EOL . $e);
85 1
            return new JsonResponse([
86 1
                'error' => RestUtils::getRestErrorCodeFromException($e),
87 1
                'message' => sprintf(
88 1
                    $this->translator->translate('Provided URL %s is invalid. Try with a different one.'),
89 1
                    $longUrl
90
                ),
91 1
            ], self::STATUS_BAD_REQUEST);
92 1
        } catch (\Exception $e) {
93 1
            $this->logger->error('Unexpected error creating shortcode.' . PHP_EOL . $e);
94 1
            return new JsonResponse([
95 1
                'error' => RestUtils::UNKNOWN_ERROR,
96 1
                'message' => $this->translator->translate('Unexpected error occurred'),
97 1
            ], self::STATUS_INTERNAL_SERVER_ERROR);
98
        }
99
    }
100
}
101