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

SingleStepCreateShortCodeAction   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 46
ccs 13
cts 13
cp 1
rs 10
wmc 5
lcom 1
cbo 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A buildUrlToShortCodeData() 0 18 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Action\ShortCode;
5
6
use Psr\Http\Message\ServerRequestInterface as Request;
7
use Psr\Log\LoggerInterface;
8
use Shlinkio\Shlink\Core\Exception\InvalidArgumentException;
9
use Shlinkio\Shlink\Core\Model\CreateShortCodeData;
10
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
11
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
12
use Zend\Diactoros\Uri;
13
use Zend\I18n\Translator\TranslatorInterface;
14
15
class SingleStepCreateShortCodeAction extends AbstractCreateShortCodeAction
16
{
17
    protected const ROUTE_PATH = '/short-codes/shorten';
18
    protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];
19
20
    /**
21
     * @var ApiKeyServiceInterface
22
     */
23
    private $apiKeyService;
24
25 4
    public function __construct(
26
        UrlShortenerInterface $urlShortener,
27
        TranslatorInterface $translator,
28
        ApiKeyServiceInterface $apiKeyService,
29
        array $domainConfig,
30
        LoggerInterface $logger = null
31
    ) {
32 4
        parent::__construct($urlShortener, $translator, $domainConfig, $logger);
33 4
        $this->apiKeyService = $apiKeyService;
34 4
    }
35
36
    /**
37
     * @param Request $request
38
     * @return CreateShortCodeData
39
     * @throws \InvalidArgumentException
40
     * @throws InvalidArgumentException
41
     */
42 4
    protected function buildUrlToShortCodeData(Request $request): CreateShortCodeData
43
    {
44 4
        $query = $request->getQueryParams();
45
46
        // Check provided API key
47 4
        $apiKey = $this->apiKeyService->getByKey($query['apiKey'] ?? '');
48 4
        if ($apiKey === null || ! $apiKey->isValid()) {
49 2
            throw new InvalidArgumentException(
50 2
                $this->translator->translate('No API key was provided or it is not valid')
51
            );
52
        }
53
54 2
        if (! isset($query['longUrl'])) {
55 1
            throw new InvalidArgumentException($this->translator->translate('A URL was not provided'));
56
        }
57
58 1
        return new CreateShortCodeData(new Uri($query['longUrl']));
59
    }
60
}
61