feat(security): add FindClient use case with Paginated search and anticipate in console commands

This commit is contained in:
Jérémy Munsch 2026-08-18 17:45:42 +02:00
parent e3462241d3
commit bad76036f1
Signed by: forge-joniko
GPG key ID: D7EFE2F5CB6CC0E4
14 changed files with 477 additions and 82 deletions

View file

@ -27,6 +27,9 @@ interface ClientRepository extends Repository
public function findByIdentifier(ClientIdentifier $identifier): ?Client;
/** @return Paginated<Client> */
public function search(string $query, Pagination $pagination): Paginated;
/** @return Paginated<Client> */
public function findAll(Pagination $pagination): Paginated;
}

View file

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Application\Security\Usecases\FindClient;
use Application\Security\Ports\Repositories\ClientRepository;
use Shared\DDD\Usecase\Input as BaseInput;
use Shared\DDD\Usecase\Usecase;
use Shared\Pagination;
use Webmozart\Assert\Assert;
/** @implements Usecase<Input, Output> */
final readonly class FindClient implements Usecase
{
public function __construct(
private ClientRepository $clientRepository,
) {
}
#[\Override]
public function execute(BaseInput $input): Output
{
Assert::isInstanceOf($input, Input::class);
$pagination = $input->pagination ?? Pagination::ofOffsetAndLimit(0, 20);
$paginated = $this->clientRepository->search($input->query, $pagination);
return new Output($paginated);
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Application\Security\Usecases\FindClient;
use Shared\DDD\Usecase\Input as BaseInput;
use Shared\Pagination;
final readonly class Input implements BaseInput
{
public function __construct(
public string $query,
public ?Pagination $pagination = null,
) {
if (trim($this->query) === '') {
throw new \InvalidArgumentException('Search query cannot be empty.');
}
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Application\Security\Usecases\FindClient;
use Application\Security\Models\Entities\Client;
use Shared\DDD\Usecase\Output as BaseOutput;
use Shared\Paginated;
final readonly class Output implements BaseOutput
{
/**
* @param Paginated<Client> $clients
*/
public function __construct(
public Paginated $clients,
) {
}
}

View file

@ -59,6 +59,38 @@ final class ApiClientRepository implements ClientRepository
);
}
#[\Override]
public function search(string $query, Pagination $pagination): Paginated
{
$trimmed = trim($query);
if ($trimmed === '') {
return new Paginated($pagination, [], 0);
}
$term = '%' . strtolower($trimmed) . '%';
$builder = ApiClient::query()
->where(function ($b) use ($term): void {
$b->whereRaw('LOWER(name) LIKE ?', [$term])
->orWhereRaw('LOWER(slug) LIKE ?', [$term])
->orWhereRaw('LOWER(identifier) LIKE ?', [$term])
->orWhereRaw('LOWER(id) LIKE ?', [$term]);
});
$total = $builder->count();
$items = $builder->forPage(
$pagination->pageNumber(),
$pagination->pageSize()
)->get();
return new Paginated(
pagination: $pagination,
items: $items->map(fn (ApiClient $apiClient) => $this->toDomain($apiClient))->all(),
total: $total,
);
}
#[\Override]
public function findAll(Pagination $pagination): Paginated
{

View file

@ -62,6 +62,35 @@ final class InMemoryClientRepository implements ClientRepository
return null;
}
#[\Override]
public function search(string $query, Pagination $pagination): Paginated
{
$trimmed = strtolower(trim($query));
if ($trimmed === '') {
return new Paginated($pagination, [], 0);
}
$matches = [];
foreach ($this->clients as $client) {
if (
str_contains(strtolower($client->name->value), $trimmed) || // Check if the query matches any of the client's properties (name, slug, identifier, or id)
str_contains(strtolower(Str::slug($client->name->value)), $trimmed) || // Check if the query matches the slug of the client's name
str_contains(strtolower($client->identifier->value), $trimmed) || // Check if the query matches the client's identifier or id
str_contains(strtolower($client->id->value), $trimmed) // Check if the query matches the client's id
) {
$matches[] = $client;
}
}
$total = count($matches);
$offset = $pagination->from();
$limit = $pagination->pageSize();
$paged = array_slice($matches, $offset, $limit);
return new Paginated($pagination, $paged, $total);
}
#[\Override]
public function existsByName(ClientName $name): bool
{

View file

@ -8,9 +8,14 @@ use Application\Security\Exceptions\ClientNotFoundException;
use Application\Security\Models\Entities\Client;
use Application\Security\Models\ValueObjects\ClientIdentifier;
use Application\Security\Ports\Repositories\ClientRepository;
use Application\Security\Usecases\FindClient\FindClient;
use Application\Security\Usecases\FindClient\Input as FindClientInput;
use Application\Security\Usecases\RegenerateClientSecret\Input;
use Application\Security\Usecases\RegenerateClientSecret\RegenerateClientSecret;
use Illuminate\Console\Command;
use Presentation\Console\Presenters\Clients\FindClientPresenter;
use Presentation\Console\Presenters\Clients\FindClientView;
use Presentation\Console\Presenters\Clients\FoundClientItem;
use Presentation\Console\Presenters\Clients\RegenerateClientSecretPresenter;
use Presentation\Console\Presenters\Clients\RegenerateClientSecretView;
use Shared\DDD\Usecase\Builder\UsecaseBuilder;
@ -61,16 +66,17 @@ final class RegenerateClientSecretCommand extends Command
public function handle(
RegenerateClientSecret $usecase,
FindClient $findClient,
UsecaseExecutor $executor,
): int {
$identifierString = $this->resolveIdentifier();
$identifierString = $this->resolveIdentifier($findClient, $executor);
if ($identifierString === null) {
return self::FAILURE;
}
try {
$clientIdentifier = $this->parseClientIdentifier($identifierString);
$clientIdentifier = $this->parseClientIdentifier($identifierString, $findClient, $executor);
$client = $this->clientRepository->findByIdentifier($clientIdentifier);
if ($client === null) {
@ -104,7 +110,7 @@ final class RegenerateClientSecretCommand extends Command
}
}
private function resolveIdentifier(): ?string
private function resolveIdentifier(FindClient $findClient, UsecaseExecutor $executor): ?string
{
$raw = $this->argument('identifier');
@ -112,38 +118,78 @@ final class RegenerateClientSecretCommand extends Command
return (string) $raw;
}
$clients = $this->clientRepository->findAll(Pagination::ofOffsetAndLimit(0, 50));
$items = $clients->getItems();
/** @var string|null $answer */
$answer = $this->anticipate(
'Search client (by name, ID, identifier, or slug):',
function (string $input) use ($findClient, $executor): array {
$trimmed = trim($input);
if ($items === []) {
$this->error('No clients found in the database.');
if ($trimmed === '') {
return [];
}
try {
/** @var FindClientView $view */
$view = UsecaseBuilder::using($executor)
->do($findClient)
->from(new FindClientInput($trimmed))
->with(new FindClientPresenter())
->run();
return array_map(
static fn (FoundClientItem $item): string => $item->identifier,
$view->clients,
);
} catch (\Throwable) {
return [];
}
}
);
if ($answer === null || trim($answer) === '') {
$this->error('No client specified.');
return null;
}
$choices = [];
foreach ($items as $client) {
$choices[$client->identifier->value] = sprintf(
'%s (%s) - %s',
$client->name->value,
$client->isActive ? 'Active' : 'Inactive',
$client->identifier->value,
);
}
$selectedDisplay = $this->choice('Which client secret would you like to regenerate?', array_values($choices));
return (string) array_search($selectedDisplay, $choices, true);
return trim($answer);
}
/**
* @throws \InvalidArgumentException
*/
private function parseClientIdentifier(string $value): ClientIdentifier
{
private function parseClientIdentifier(
string $value,
FindClient $findClient,
UsecaseExecutor $executor,
): ClientIdentifier {
try {
return new ClientIdentifier($value);
} catch (\InvalidArgumentException) {
try {
/** @var FindClientView $view */
$view = UsecaseBuilder::using($executor)
->do($findClient)
->from(new FindClientInput($value))
->with(new FindClientPresenter())
->run();
if (count($view->clients) === 1) {
return new ClientIdentifier($view->clients[0]->identifier);
}
if (count($view->clients) > 1) {
foreach ($view->clients as $found) {
if (
strcasecmp($found->name, $value) === 0 || strcasecmp($found->id, $value) === 0
) {
return new ClientIdentifier($found->identifier);
}
}
}
} catch (\Throwable) {
}
throw new \InvalidArgumentException("Invalid client identifier '{$value}'. Expected a valid client identifier.");
}
}

View file

@ -8,9 +8,14 @@ use Application\Security\Exceptions\ClientNotFoundException;
use Application\Security\Models\Entities\Client;
use Application\Security\Models\ValueObjects\ClientIdentifier;
use Application\Security\Ports\Repositories\ClientRepository;
use Application\Security\Usecases\FindClient\FindClient;
use Application\Security\Usecases\FindClient\Input as FindClientInput;
use Application\Security\Usecases\ToggleClientStatus\Input;
use Application\Security\Usecases\ToggleClientStatus\SetClientStatus;
use Illuminate\Console\Command;
use Presentation\Console\Presenters\Clients\FindClientPresenter;
use Presentation\Console\Presenters\Clients\FindClientView;
use Presentation\Console\Presenters\Clients\FoundClientItem;
use Presentation\Console\Presenters\Clients\SetClientStatusPresenter;
use Shared\DDD\Usecase\Builder\UsecaseBuilder;
use Shared\DDD\Usecase\Builder\UsecaseExecutor;
@ -68,16 +73,17 @@ final class ToggleClientStatusCommand extends Command
public function handle(
SetClientStatus $usecase,
FindClient $findClient,
UsecaseExecutor $executor,
): int {
$identifierString = $this->resolveIdentifier();
$identifierString = $this->resolveIdentifier($findClient, $executor);
if ($identifierString === null) {
return self::FAILURE;
}
try {
$clientIdentifier = $this->parseClientIdentifier($identifierString);
$clientIdentifier = $this->parseClientIdentifier($identifierString, $findClient, $executor);
$desiredStatus = $this->resolveDesiredStatus($clientIdentifier);
$input = new Input($clientIdentifier, $desiredStatus);
@ -97,7 +103,7 @@ final class ToggleClientStatusCommand extends Command
}
}
private function resolveIdentifier(): ?string
private function resolveIdentifier(FindClient $findClient, UsecaseExecutor $executor): ?string
{
$raw = $this->argument('identifier');
@ -105,38 +111,78 @@ final class ToggleClientStatusCommand extends Command
return (string) $raw;
}
$clients = $this->clientRepository->findAll(Pagination::ofOffsetAndLimit(0, 50));
$items = $clients->getItems();
/** @var string|null $answer */
$answer = $this->anticipate(
'Search client (by name, ID, identifier, or slug):',
function (string $input) use ($findClient, $executor): array {
$trimmed = trim($input);
if ($items === []) {
$this->error('No clients found in the database.');
if ($trimmed === '') {
return [];
}
try {
/** @var FindClientView $view */
$view = UsecaseBuilder::using($executor)
->do($findClient)
->from(new FindClientInput($trimmed))
->with(new FindClientPresenter())
->run();
return array_map(
static fn (FoundClientItem $item): string => $item->identifier,
$view->clients,
);
} catch (\Throwable) {
return [];
}
}
);
if ($answer === null || trim($answer) === '') {
$this->error('No client specified.');
return null;
}
$choices = [];
foreach ($items as $client) {
$choices[$client->identifier->value] = sprintf(
'%s (%s) - %s',
$client->name->value,
$client->isActive ? 'Active' : 'Inactive',
$client->identifier->value,
);
}
$selectedDisplay = $this->choice('Which client would you like to update?', array_values($choices));
return (string) array_search($selectedDisplay, $choices, true);
return trim($answer);
}
/**
* @throws \InvalidArgumentException
*/
private function parseClientIdentifier(string $value): ClientIdentifier
{
private function parseClientIdentifier(
string $value,
FindClient $findClient,
UsecaseExecutor $executor,
): ClientIdentifier {
try {
return new ClientIdentifier($value);
} catch (\InvalidArgumentException) {
try {
/** @var FindClientView $view */
$view = UsecaseBuilder::using($executor)
->do($findClient)
->from(new FindClientInput($value))
->with(new FindClientPresenter())
->run();
if (count($view->clients) === 1) {
return new ClientIdentifier($view->clients[0]->identifier);
}
if (count($view->clients) > 1) {
foreach ($view->clients as $found) {
if (
strcasecmp($found->name, $value) === 0 || strcasecmp($found->id, $value) === 0
) {
return new ClientIdentifier($found->identifier);
}
}
}
} catch (\Throwable) {
}
throw new \InvalidArgumentException("Invalid client identifier '{$value}'. Expected a valid client identifier.");
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Presentation\Console\Presenters\Clients;
use Application\Security\Models\Entities\Client;
use Application\Security\Usecases\FindClient\Output;
use Shared\DDD\Usecase\Output as UsecaseOutput;
use Shared\DDD\Usecase\Presenter;
use Webmozart\Assert\Assert;
/** @implements Presenter<Output, FindClientView> */
final readonly class FindClientPresenter implements Presenter
{
#[\Override]
public function present(UsecaseOutput $output): object
{
Assert::isInstanceOf($output, Output::class);
return new FindClientView(
clients: array_values(array_map(
static fn (Client $client): FoundClientItem => new FoundClientItem(
id: $client->id->value,
name: $client->name->value,
identifier: $client->identifier->value,
isActive: $client->isActive,
display: sprintf(
'%s (%s) - %s',
$client->name->value,
$client->isActive ? 'Active' : 'Inactive',
$client->identifier->value,
),
),
$output->clients->getItems(),
)),
total: $output->clients->getTotal(),
);
}
}

View file

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Presentation\Console\Presenters\Clients;
final readonly class FindClientView
{
/**
* @param list<FoundClientItem> $clients
*/
public function __construct(
public array $clients,
public int $total,
) {
}
}

View file

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Presentation\Console\Presenters\Clients;
final readonly class FoundClientItem
{
public function __construct(
public string $id,
public string $name,
public string $identifier,
public bool $isActive,
public string $display,
) {
}
}

View file

@ -94,63 +94,41 @@ describe('RegenerateClientSecretCommand', function (): void {
expect($client->secret->value)->toBe($oldSecret);
});
it('interactively prompts to select client when no argument is provided', function (): void {
it('interactively prompts and searches client when no argument is provided', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
ApiClient::query()->delete();
$identifier = 'arcadia_id_' . str_repeat('d', 32);
$oldSecret = 'arcadia_sec_' . str_repeat('3', 86);
$identifier1 = 'arcadia_id_' . str_repeat('c', 32);
$identifier2 = 'arcadia_id_' . str_repeat('d', 32);
$oldSecret2 = 'arcadia_sec_' . str_repeat('3', 86);
ApiClient::query()->create([
$client = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Client One',
'slug' => 'client-one',
'identifier' => $identifier1,
'secret' => 'arcadia_sec_' . str_repeat('4', 86),
'name' => 'Searchable Client',
'slug' => 'searchable-client',
'identifier' => $identifier,
'secret' => $oldSecret,
'is_active' => true,
]);
$client2 = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Client Two',
'slug' => 'client-two',
'identifier' => $identifier2,
'secret' => $oldSecret2,
'is_active' => false,
]);
// WHEN
$this->artisan('client:regenerate-secret')
// THEN
->expectsChoice(
'Which client secret would you like to regenerate?',
"Client Two (Inactive) - {$identifier2}",
[
"Client One (Active) - {$identifier1}",
"Client Two (Inactive) - {$identifier2}",
],
)
->expectsQuestion('Search client (by name, ID, identifier, or slug):', $identifier)
->expectsConfirmation('Do you want to proceed?', 'yes')
->expectsOutputToContain("Secret for client '{$identifier2}' regenerated successfully.")
->expectsOutputToContain("Secret for client '{$identifier}' regenerated successfully.")
->assertSuccessful();
$client2->refresh();
expect($client2->secret->value)->not->toBe($oldSecret2);
$client->refresh();
expect($client->secret->value)->not->toBe($oldSecret);
});
it('outputs an error when no clients exist in database during interactive prompt', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
ApiClient::query()->delete();
// WHEN
it('outputs an error when no input provided during interactive prompt', function (): void {
// GIVEN & WHEN
$this->artisan('client:regenerate-secret')
// THEN
->expectsOutput('No clients found in the database.')
->expectsQuestion('Search client (by name, ID, identifier, or slug):', '')
->expectsOutput('No client specified.')
->assertFailed();
});

View file

@ -144,6 +144,30 @@ describe('ToggleClientStatusCommand', function (): void {
->assertFailed();
});
it('prompts and searches client interactively when no identifier is passed', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$identifier = 'arcadia_id_' . str_repeat('k', 32);
$client = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Interactive Gateway',
'slug' => 'interactive-gateway',
'identifier' => $identifier,
'secret' => 'arcadia_sec_' . str_repeat('k', 86),
'is_active' => true,
]);
// WHEN
$this->artisan('client:toggle-status')
// THEN
->expectsQuestion('Search client (by name, ID, identifier, or slug):', $identifier)
->expectsOutput("Client 'Interactive Gateway' (ID: {$client->id}) is now Inactive.")
->assertSuccessful();
$client->refresh();
expect($client->is_active)->toBeFalse();
});
it('provides autocompletion suggestions for identifier', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */

View file

@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Application\Security\Usecases\FindClient;
use Application\Security\Models\Entities\Client;
use Application\Security\Models\ValueObjects\ClientIdentifier;
use Application\Security\Models\ValueObjects\ClientName;
use Application\Security\Models\ValueObjects\ClientSecret;
use Application\Security\Models\ValueObjects\Entities\ClientId;
use Application\Security\Usecases\FindClient\FindClient;
use Application\Security\Usecases\FindClient\Input;
use Application\Security\Usecases\FindClient\Output;
use Infra\Adapters\Repositories\InMemoryClientRepository;
use Ramsey\Uuid\Uuid;
use Shared\Paginated;
use Shared\Pagination;
covers(
FindClient::class,
Input::class,
Output::class,
);
describe('FindClient Usecase Unit Tests', function (): void {
$repository = new InMemoryClientRepository();
beforeEach(function () use ($repository): void {
$repository->clear();
});
it('searches and finds clients matching query with pagination', function () use ($repository): void {
// GIVEN
$client1 = Client::hydrate(
id: new ClientId(Uuid::uuid7()),
name: new ClientName('Production Gateway'),
identifier: new ClientIdentifier('arcadia_id_' . str_repeat('a', 32)),
secret: new ClientSecret('arcadia_sec_' . str_repeat('1', 86)),
isActive: true,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
);
$client2 = Client::hydrate(
id: new ClientId(Uuid::uuid7()),
name: new ClientName('Staging Hub'),
identifier: new ClientIdentifier('arcadia_id_' . str_repeat('b', 32)),
secret: new ClientSecret('arcadia_sec_' . str_repeat('2', 86)),
isActive: false,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
);
$repository->add($client1, $client2);
$usecase = new FindClient($repository);
// WHEN
$resultByName = $usecase->execute(new Input('production', Pagination::ofOffsetAndLimit(0, 10)));
$resultByIdentifier = $usecase->execute(new Input('arcadia_id_' . str_repeat('b', 32)));
$resultBySlug = $usecase->execute(new Input('staging-hub'));
// THEN
expect($resultByName)->toBeInstanceOf(Output::class)
->and($resultByName->clients)->toBeInstanceOf(Paginated::class)
->and($resultByName->clients->getTotal())->toBe(1)
->and($resultByName->clients->getItems()[0]->name->value)->toBe('Production Gateway')
->and($resultByIdentifier->clients->getTotal())->toBe(1)
->and($resultByIdentifier->clients->getItems()[0]->name->value)->toBe('Staging Hub')
->and($resultBySlug->clients->getTotal())->toBe(1)
->and($resultBySlug->clients->getItems()[0]->name->value)->toBe('Staging Hub');
});
it('throws InvalidArgumentException when query is empty', function (): void {
// GIVEN & WHEN & THEN
expect(fn () => new Input(' '))
->toThrow(\InvalidArgumentException::class, 'Search query cannot be empty.');
});
it('returns empty paginated result when no clients match', function () use ($repository): void {
// GIVEN
$usecase = new FindClient($repository);
// WHEN
$result = $usecase->execute(new Input('non-existent'));
// THEN
expect($result->clients)->toBeInstanceOf(Paginated::class)
->and($result->clients->getTotal())->toBe(0)
->and($result->clients->getItems())->toBeEmpty();
});
});