Move logic to determine if a new key has a duplicated name to the APiKeyService

This commit is contained in:
Alejandro Celaya
2024-11-08 09:03:50 +01:00
parent b08c498b13
commit 6f837b3b91
6 changed files with 38 additions and 50 deletions

View File

@@ -21,7 +21,13 @@ readonly class ApiKeyService implements ApiKeyServiceInterface
public function create(ApiKeyMeta $apiKeyMeta): ApiKey
{
// TODO If name is auto-generated, do not throw. Instead, re-generate a new key
$apiKey = ApiKey::fromMeta($apiKeyMeta);
if ($this->existsWithName($apiKey->name)) {
throw new InvalidArgumentException(
sprintf('Another API key with name "%s" already exists', $apiKeyMeta->name),
);
}
$this->em->persist($apiKey);
$this->em->flush();
@@ -77,14 +83,6 @@ readonly class ApiKeyService implements ApiKeyServiceInterface
return $this->repo->findBy($conditions);
}
/**
* @inheritDoc
*/
public function existsWithName(string $apiKeyName): bool
{
return $this->repo->count(['name' => $apiKeyName]) > 0;
}
/**
* @inheritDoc
* @todo This method should be transactional and to a SELECT ... FROM UPDATE when checking if the new name exists,
@@ -120,4 +118,9 @@ readonly class ApiKeyService implements ApiKeyServiceInterface
{
return $this->repo->findOneBy(['key' => ApiKey::hashKey($key)]);
}
private function existsWithName(string $apiKeyName): bool
{
return $this->repo->count(['name' => $apiKeyName]) > 0;
}
}