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

87 lines
2.1 KiB
PHP
Raw Normal View History

2016-08-06 13:18:27 +02:00
<?php
2019-10-05 17:26:10 +02:00
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 Doctrine\ORM\EntityManagerInterface;
use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
use Shlinkio\Shlink\Rest\ApiKey\Model\ApiKeyMeta;
use Shlinkio\Shlink\Rest\ApiKey\Repository\ApiKeyRepositoryInterface;
2016-08-06 13:18:27 +02:00
use Shlinkio\Shlink\Rest\Entity\ApiKey;
readonly class ApiKeyService implements ApiKeyServiceInterface
2016-08-06 13:18:27 +02:00
{
public function __construct(private EntityManagerInterface $em, private ApiKeyRepositoryInterface $repo)
2016-08-06 13:18:27 +02:00
{
}
2023-09-19 09:10:17 +02:00
public function create(ApiKeyMeta $apiKeyMeta): ApiKey
{
$apiKey = ApiKey::fromMeta($apiKeyMeta);
2016-08-06 13:18:27 +02:00
2023-09-19 09:10:17 +02:00
$this->em->persist($apiKey);
$this->em->flush();
2016-08-06 13:18:27 +02:00
2023-09-19 09:10:17 +02:00
return $apiKey;
}
2024-10-28 22:27:30 +01:00
public function createInitial(string $key): ApiKey|null
{
return $this->repo->createInitialApiKey($key);
}
2020-11-08 11:28:27 +01:00
public function check(string $key): ApiKeyCheckResult
2016-08-06 13:18:27 +02:00
{
$apiKey = $this->findByKey($key);
2020-11-08 11:28:27 +01:00
return new ApiKeyCheckResult($apiKey);
2016-08-06 13:18:27 +02:00
}
/**
* @inheritDoc
2016-08-06 13:18:27 +02:00
*/
public function disableByName(string $apiKeyName): ApiKey
{
return $this->disableApiKey($this->findByName($apiKeyName));
}
/**
* @inheritDoc
*/
public function disableByKey(string $key): ApiKey
{
return $this->disableApiKey($this->findByKey($key));
}
private function disableApiKey(ApiKey|null $apiKey): ApiKey
2016-08-06 13:18:27 +02:00
{
2017-12-27 16:23:54 +01:00
if ($apiKey === null) {
throw new InvalidArgumentException('Provided API key does not exist and can\'t be disabled');
2016-08-06 13:18:27 +02:00
}
$apiKey->disable();
$this->em->flush();
2016-08-06 13:18:27 +02:00
return $apiKey;
}
/**
* @return ApiKey[]
*/
2018-07-31 19:53:59 +02:00
public function listKeys(bool $enabledOnly = false): array
{
$conditions = $enabledOnly ? ['enabled' => true] : [];
return $this->repo->findBy($conditions);
}
private function findByKey(string $key): ApiKey|null
{
return $this->repo->findOneBy(['key' => ApiKey::hashKey($key)]);
}
private function findByName(string $name): ApiKey|null
{
return $this->repo->findOneBy(['name' => $name]);
}
2016-08-06 13:18:27 +02:00
}