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

buildUrlToShortCodeData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 18
ccs 9
cts 9
cp 1
crap 4
rs 9.2
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