diff --git a/src/Application/Security/Ports/Repositories/ClientRepository.php b/src/Application/Security/Ports/Repositories/ClientRepository.php index 85aa184..2a6a4fa 100644 --- a/src/Application/Security/Ports/Repositories/ClientRepository.php +++ b/src/Application/Security/Ports/Repositories/ClientRepository.php @@ -27,6 +27,9 @@ interface ClientRepository extends Repository public function findByIdentifier(ClientIdentifier $identifier): ?Client; + /** @return Paginated */ + public function search(string $query, Pagination $pagination): Paginated; + /** @return Paginated */ public function findAll(Pagination $pagination): Paginated; } diff --git a/src/Application/Security/Usecases/FindClient/FindClient.php b/src/Application/Security/Usecases/FindClient/FindClient.php new file mode 100644 index 0000000..491ae09 --- /dev/null +++ b/src/Application/Security/Usecases/FindClient/FindClient.php @@ -0,0 +1,31 @@ + */ +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); + } +} diff --git a/src/Application/Security/Usecases/FindClient/Input.php b/src/Application/Security/Usecases/FindClient/Input.php new file mode 100644 index 0000000..88ff9bb --- /dev/null +++ b/src/Application/Security/Usecases/FindClient/Input.php @@ -0,0 +1,20 @@ +query) === '') { + throw new \InvalidArgumentException('Search query cannot be empty.'); + } + } +} diff --git a/src/Application/Security/Usecases/FindClient/Output.php b/src/Application/Security/Usecases/FindClient/Output.php new file mode 100644 index 0000000..ad045f9 --- /dev/null +++ b/src/Application/Security/Usecases/FindClient/Output.php @@ -0,0 +1,20 @@ + $clients + */ + public function __construct( + public Paginated $clients, + ) { + } +} diff --git a/src/Infra/Adapters/Repositories/ApiClientRepository.php b/src/Infra/Adapters/Repositories/ApiClientRepository.php index d71298a..ccff9d9 100644 --- a/src/Infra/Adapters/Repositories/ApiClientRepository.php +++ b/src/Infra/Adapters/Repositories/ApiClientRepository.php @@ -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 { diff --git a/src/Infra/Adapters/Repositories/InMemoryClientRepository.php b/src/Infra/Adapters/Repositories/InMemoryClientRepository.php index 31c8a52..a897b88 100644 --- a/src/Infra/Adapters/Repositories/InMemoryClientRepository.php +++ b/src/Infra/Adapters/Repositories/InMemoryClientRepository.php @@ -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 { diff --git a/src/Presentation/Console/Commands/RegenerateClientSecretCommand.php b/src/Presentation/Console/Commands/RegenerateClientSecretCommand.php index 79a9df4..9fa7152 100644 --- a/src/Presentation/Console/Commands/RegenerateClientSecretCommand.php +++ b/src/Presentation/Console/Commands/RegenerateClientSecretCommand.php @@ -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."); } } diff --git a/src/Presentation/Console/Commands/ToggleClientStatusCommand.php b/src/Presentation/Console/Commands/ToggleClientStatusCommand.php index 7f71bac..4a30553 100644 --- a/src/Presentation/Console/Commands/ToggleClientStatusCommand.php +++ b/src/Presentation/Console/Commands/ToggleClientStatusCommand.php @@ -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."); } } diff --git a/src/Presentation/Console/Presenters/Clients/FindClientPresenter.php b/src/Presentation/Console/Presenters/Clients/FindClientPresenter.php new file mode 100644 index 0000000..1454615 --- /dev/null +++ b/src/Presentation/Console/Presenters/Clients/FindClientPresenter.php @@ -0,0 +1,40 @@ + */ +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(), + ); + } +} diff --git a/src/Presentation/Console/Presenters/Clients/FindClientView.php b/src/Presentation/Console/Presenters/Clients/FindClientView.php new file mode 100644 index 0000000..186abd9 --- /dev/null +++ b/src/Presentation/Console/Presenters/Clients/FindClientView.php @@ -0,0 +1,17 @@ + $clients + */ + public function __construct( + public array $clients, + public int $total, + ) { + } +} diff --git a/src/Presentation/Console/Presenters/Clients/FoundClientItem.php b/src/Presentation/Console/Presenters/Clients/FoundClientItem.php new file mode 100644 index 0000000..5d7d91f --- /dev/null +++ b/src/Presentation/Console/Presenters/Clients/FoundClientItem.php @@ -0,0 +1,17 @@ +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(); }); diff --git a/tests/Feature/Console/Commands/ToggleClientStatusCommandTest.php b/tests/Feature/Console/Commands/ToggleClientStatusCommandTest.php index 291904c..a184e8f 100644 --- a/tests/Feature/Console/Commands/ToggleClientStatusCommandTest.php +++ b/tests/Feature/Console/Commands/ToggleClientStatusCommandTest.php @@ -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 */ diff --git a/tests/Unit/Application/Security/Usecases/FindClient/FindClientTest.php b/tests/Unit/Application/Security/Usecases/FindClient/FindClientTest.php new file mode 100644 index 0000000..ecdaafe --- /dev/null +++ b/tests/Unit/Application/Security/Usecases/FindClient/FindClientTest.php @@ -0,0 +1,92 @@ +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(); + }); +});