Completed
Push — master ( 224127...d5dc6c )
by Alejandro
28s
created

ApiKeyHeaderPlugin   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A verify() 0 12 2
A update() 0 4 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Authentication\Plugin;
5
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
9
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
10
use Shlinkio\Shlink\Rest\Util\RestUtils;
11
use Zend\I18n\Translator\TranslatorInterface;
12
13
class ApiKeyHeaderPlugin implements AuthenticationPluginInterface
14
{
15
    public const HEADER_NAME = 'X-Api-Key';
16
17
    /**
18
     * @var ApiKeyServiceInterface
19
     */
20
    private $apiKeyService;
21
    /**
22
     * @var TranslatorInterface
23
     */
24
    private $translator;
25
26 3
    public function __construct(ApiKeyServiceInterface $apiKeyService, TranslatorInterface $translator)
27
    {
28 3
        $this->apiKeyService = $apiKeyService;
29 3
        $this->translator = $translator;
30 3
    }
31
32
    /**
33
     * @throws VerifyAuthenticationException
34
     */
35 2
    public function verify(ServerRequestInterface $request): void
36
    {
37 2
        $apiKey = $request->getHeaderLine(self::HEADER_NAME);
38 2
        if ($this->apiKeyService->check($apiKey)) {
39 1
            return;
40
        }
41
42 1
        throw VerifyAuthenticationException::withError(
43 1
            RestUtils::INVALID_API_KEY_ERROR,
44 1
            $this->translator->translate('Provided API key does not exist or is invalid.')
45
        );
46
    }
47
48 1
    public function update(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
49
    {
50 1
        return $response;
51
    }
52
}
53