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

SingleStepCreateShortCodeAction   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

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