ApiKeyService::check()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Rest\Service;
6
7
use Cake\Chronos\Chronos;
8
use Doctrine\ORM\EntityManagerInterface;
9
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
10
use Shlinkio\Shlink\Rest\Entity\ApiKey;
11
12
use function sprintf;
13
14
class ApiKeyService implements ApiKeyServiceInterface
15
{
16
    private EntityManagerInterface $em;
17
18 11
    public function __construct(EntityManagerInterface $em)
19
    {
20 11
        $this->em = $em;
21 11
    }
22
23 2
    public function create(?Chronos $expirationDate = null): ApiKey
24
    {
25 2
        $key = new ApiKey($expirationDate);
26 2
        $this->em->persist($key);
27 2
        $this->em->flush();
28
29 2
        return $key;
30
    }
31
32 5
    public function check(string $key): bool
33
    {
34
        /** @var ApiKey|null $apiKey */
35 5
        $apiKey = $this->getByKey($key);
36 5
        return $apiKey !== null && $apiKey->isValid();
37
    }
38
39
    /**
40
     * @throws InvalidArgumentException
41
     */
42 2
    public function disable(string $key): ApiKey
43
    {
44
        /** @var ApiKey|null $apiKey */
45 2
        $apiKey = $this->getByKey($key);
46 2
        if ($apiKey === null) {
47 1
            throw new InvalidArgumentException(sprintf('API key "%s" does not exist and can\'t be disabled', $key));
48
        }
49
50 1
        $apiKey->disable();
51 1
        $this->em->flush();
52 1
        return $apiKey;
53
    }
54
55
    /**
56
     * @return ApiKey[]
57
     */
58 2
    public function listKeys(bool $enabledOnly = false): array
59
    {
60 2
        $conditions = $enabledOnly ? ['enabled' => true] : [];
61
        /** @var ApiKey[] $apiKeys */
62 2
        $apiKeys = $this->em->getRepository(ApiKey::class)->findBy($conditions);
63 2
        return $apiKeys;
64
    }
65
66 7
    public function getByKey(string $key): ?ApiKey
67
    {
68
        /** @var ApiKey|null $apiKey */
69 7
        $apiKey = $this->em->getRepository(ApiKey::class)->findOneBy([
70 7
            'key' => $key,
71
        ]);
72 7
        return $apiKey;
73
    }
74
}
75