Completed
Pull Request — master (#148)
by Alejandro
09:03 queued 02:46
created

SingleStepCreateShortCodeAction::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 5
dl 0
loc 10
ccs 0
cts 4
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
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
    public function __construct(
26
        UrlShortenerInterface $urlShortener,
27
        TranslatorInterface $translator,
28
        ApiKeyServiceInterface $apiKeyService,
29
        array $domainConfig,
30
        LoggerInterface $logger = null
31
    ) {
32
        parent::__construct($urlShortener, $translator, $domainConfig, $logger);
33
        $this->apiKeyService = $apiKeyService;
34
    }
35
36
    /**
37
     * @param Request $request
38
     * @return CreateShortCodeData
39
     * @throws \InvalidArgumentException
40
     * @throws InvalidArgumentException
41
     */
42
    protected function buildUrlToShortCodeData(Request $request): CreateShortCodeData
43
    {
44
        $query = $request->getQueryParams();
45
46
        // Check provided API key
47
        $apiKey = $this->apiKeyService->getByKey($query['apiKey'] ?? '');
48
        if ($apiKey === null || ! $apiKey->isValid()) {
49
            throw new InvalidArgumentException(
50
                $this->translator->translate('No API key was provided or it is not valid')
51
            );
52
        }
53
54
        if (! isset($query['longUrl'])) {
55
            throw new InvalidArgumentException($this->translator->translate('A URL was not provided'));
56
        }
57
58
        return new CreateShortCodeData(new Uri($query['longUrl']));
59
    }
60
}
61