shlink/module/Rest/src/Service/ApiKeyService.php

76 lines
1.8 KiB
PHP
Raw Normal View History

2016-08-06 13:18:27 +02:00
<?php
2017-10-12 10:13:20 +02:00
declare(strict_types=1);
2016-08-06 13:18:27 +02:00
namespace Shlinkio\Shlink\Rest\Service;
use Cake\Chronos\Chronos;
2016-08-06 13:18:27 +02:00
use Doctrine\ORM\EntityManagerInterface;
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use function sprintf;
2016-08-06 13:18:27 +02:00
class ApiKeyService implements ApiKeyServiceInterface
{
/**
* @var EntityManagerInterface
*/
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function create(?Chronos $expirationDate = null): ApiKey
2016-08-06 13:18:27 +02:00
{
$key = new ApiKey($expirationDate);
2016-08-06 13:18:27 +02:00
$this->em->persist($key);
$this->em->flush();
return $key;
}
2018-07-31 19:53:59 +02:00
public function check(string $key): bool
2016-08-06 13:18:27 +02:00
{
2017-12-27 16:23:54 +01:00
/** @var ApiKey|null $apiKey */
$apiKey = $this->getByKey($key);
2017-12-27 16:23:54 +01:00
return $apiKey !== null && $apiKey->isValid();
2016-08-06 13:18:27 +02:00
}
/**
2017-12-27 16:23:54 +01:00
* @throws InvalidArgumentException
2016-08-06 13:18:27 +02:00
*/
2018-07-31 19:53:59 +02:00
public function disable(string $key): ApiKey
2016-08-06 13:18:27 +02:00
{
2017-12-27 16:23:54 +01:00
/** @var ApiKey|null $apiKey */
$apiKey = $this->getByKey($key);
2017-12-27 16:23:54 +01:00
if ($apiKey === null) {
2016-08-06 13:18:27 +02:00
throw new InvalidArgumentException(sprintf('API key "%s" does not exist and can\'t be disabled', $key));
}
$apiKey->disable();
$this->em->flush();
return $apiKey;
}
/**
* @return ApiKey[]
*/
2018-07-31 19:53:59 +02:00
public function listKeys(bool $enabledOnly = false): array
{
$conditions = $enabledOnly ? ['enabled' => true] : [];
2018-07-31 19:53:59 +02:00
/** @var ApiKey[] $apiKeys */
$apiKeys = $this->em->getRepository(ApiKey::class)->findBy($conditions);
return $apiKeys;
}
2018-07-31 19:53:59 +02:00
public function getByKey(string $key): ?ApiKey
{
2017-12-27 16:23:54 +01:00
/** @var ApiKey|null $apiKey */
$apiKey = $this->em->getRepository(ApiKey::class)->findOneBy([
'key' => $key,
]);
2017-12-27 16:23:54 +01:00
return $apiKey;
}
2016-08-06 13:18:27 +02:00
}