feat(console): add ToggleClientStatus command and related logic

- Implemented command to toggle client status via console.
- Introduced SetClientStatus use case for managing client activation.
- Added presenters and views for command output.
- Created tests for command functionality and edge cases.
This commit is contained in:
Jérémy Munsch 2026-08-18 16:56:15 +02:00
parent 2ac8578fe0
commit 43758922ad
Signed by: forge-joniko
GPG key ID: D7EFE2F5CB6CC0E4
13 changed files with 632 additions and 38 deletions

View file

@ -77,9 +77,9 @@ final class Client implements Entity
$this->updatedAt = new \DateTimeImmutable();
}
public function toggleStatus(): bool
public function setActive(bool $status): bool
{
$this->isActive = ! $this->isActive;
$this->isActive = $status;
$this->updatedAt = new \DateTimeImmutable();
return $this->isActive;

View file

@ -27,7 +27,7 @@ final readonly class RegenerateClientSecret implements Usecase
{
Assert::isInstanceOf($input, Input::class);
$client = $this->clientRepository->find($input->clientId) ?? throw new ClientNotFoundException();
$client = $this->clientRepository->find($input->clientId) ?? throw ClientNotFoundException::forClient($input->clientId->value);
$newSecret = $this->credentialGenerator->generateSecret();
$client->regenerateSecret($newSecret);

View file

@ -4,12 +4,13 @@ declare(strict_types=1);
namespace Application\Security\Usecases\ToggleClientStatus;
use Application\Security\Models\ValueObjects\Entities\ClientId;
use Application\Security\Models\ValueObjects\ClientIdentifier;
final readonly class Input implements \Shared\DDD\Usecase\Input
{
public function __construct(
public ClientId $clientId,
public ClientIdentifier $clientIdentifier,
public bool $desiredStatus,
) {
}
}

View file

@ -13,7 +13,7 @@ use Shared\DDD\Usecase\Usecase;
use Webmozart\Assert\Assert;
/** @implements Usecase<\Application\Security\Usecases\ToggleClientStatus\Input, \Application\Security\Usecases\ToggleClientStatus\Output> */
final readonly class ToggleClientStatus implements Usecase
final readonly class SetClientStatus implements Usecase
{
public function __construct(
private ClientRepository $clientRepository,
@ -26,17 +26,22 @@ final readonly class ToggleClientStatus implements Usecase
{
Assert::isInstanceOf($input, Input::class);
$client = $this->clientRepository->find($input->clientId) ?? throw new ClientNotFoundException();
$client = $this->clientRepository->findByIdentifier($input->clientIdentifier)
?? throw ClientNotFoundException::forClient($input->clientIdentifier->value);
$isActive = $client->toggleStatus();
$this->clientRepository->persist($client);
$changed = $client->isActive !== $input->desiredStatus;
$isActive = $client->setActive($input->desiredStatus);
$this->dispatcher->dispatch(new ClientStatusToggled(
clientId: $client->id,
clientIdentifier: $client->identifier,
isActive: $isActive,
toggledAt: new \DateTimeImmutable(),
));
if ($changed) {
$this->clientRepository->persist($client);
$this->dispatcher->dispatch(new ClientStatusToggled(
clientId: $client->id,
clientIdentifier: $client->identifier,
isActive: $isActive,
toggledAt: new \DateTimeImmutable(),
));
}
return new Output(
clientId: $client->id,

View file

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Infra\Adapters\Events;
use Illuminate\Contracts\Events\Dispatcher;
use Shared\DDD\Event\DomainEventDispatcher;
use Shared\DDD\Event\Event;
final readonly class LaravelDomainEventDispatcher implements DomainEventDispatcher
{
public function __construct(
private Dispatcher $events,
) {
}
#[\Override]
public function dispatch(Event $event): void
{
$this->events->dispatch($event);
}
}

View file

@ -13,7 +13,9 @@ use Infra\Adapters\Directories\EloquentEmployeeDirectory;
use Infra\Adapters\Directories\EloquentIncoCompositionDirectory;
use Infra\Adapters\Directories\EloquentIncoSheetDirectory;
use Infra\Adapters\Directories\EloquentIncoShortSheetDirectory;
use Infra\Adapters\Events\LaravelDomainEventDispatcher;
use Infra\Usecase\LaravelExecutor;
use Shared\DDD\Event\DomainEventDispatcher;
use Shared\DDD\Usecase\Builder\UsecaseExecutor;
class DomainServiceProvider extends ServiceProvider
@ -25,6 +27,7 @@ class DomainServiceProvider extends ServiceProvider
$this->app->bind(IncoSheetDirectory::class, EloquentIncoSheetDirectory::class);
$this->app->bind(IncoShortSheetDirectory::class, EloquentIncoShortSheetDirectory::class);
$this->app->bind(IncoCompositionDirectory::class, EloquentIncoCompositionDirectory::class);
$this->app->bind(DomainEventDispatcher::class, LaravelDomainEventDispatcher::class);
$this->app->singleton(UsecaseExecutor::class, LaravelExecutor::class);
}
}

View file

@ -0,0 +1,163 @@
<?php
declare(strict_types=1);
namespace Presentation\Console\Commands;
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\ToggleClientStatus\Input;
use Application\Security\Usecases\ToggleClientStatus\SetClientStatus;
use Illuminate\Console\Command;
use Presentation\Console\Presenters\Clients\SetClientStatusPresenter;
use Shared\DDD\Usecase\Builder\UsecaseBuilder;
use Shared\DDD\Usecase\Builder\UsecaseExecutor;
use Shared\Pagination;
use Symfony\Component\Console\Completion\CompletionInput;
use Symfony\Component\Console\Completion\CompletionSuggestions;
use Symfony\Component\Console\Completion\Suggestion;
final class ToggleClientStatusCommand extends Command
{
/**
* @var string
*/
protected $signature = 'client:toggle-status
{identifier? : The identifier of the client}
{status? : The desired status of the client (activate|deactivate)}';
/**
* @var string
*/
protected $description = 'Toggle the status of an API client';
public function __construct(
private readonly ClientRepository $clientRepository,
) {
parent::__construct();
}
#[\Override]
public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
{
parent::complete($input, $suggestions);
if ($input->mustSuggestArgumentValuesFor('identifier')) {
$clients = $this->clientRepository->findAll(Pagination::ofOffsetAndLimit(0, 100));
/** @var list<Suggestion> $items */
$items = array_map(
static fn (Client $client): Suggestion => new Suggestion(
value: $client->identifier->value,
description: sprintf('%s (%s)', $client->name->value, $client->isActive ? 'Active' : 'Inactive'),
),
$clients->getItems(),
);
$suggestions->suggestValues($items);
}
if ($input->mustSuggestArgumentValuesFor('status')) {
$suggestions->suggestValues([
new Suggestion('activate', 'Activate the client'),
new Suggestion('deactivate', 'Deactivate the client'),
]);
}
}
public function handle(
SetClientStatus $usecase,
UsecaseExecutor $executor,
): int {
$identifierString = $this->resolveIdentifier();
if ($identifierString === null) {
return self::FAILURE;
}
try {
$clientIdentifier = $this->parseClientIdentifier($identifierString);
$desiredStatus = $this->resolveDesiredStatus($clientIdentifier);
$input = new Input($clientIdentifier, $desiredStatus);
$view = UsecaseBuilder::using($executor)
->do($usecase)
->from($input)
->with(new SetClientStatusPresenter())
->run();
$this->info($view->message);
return self::SUCCESS;
} catch (ClientNotFoundException | \InvalidArgumentException $e) {
$this->error($e->getMessage());
return self::FAILURE;
}
}
private function resolveIdentifier(): ?string
{
$raw = $this->argument('identifier');
if ($raw !== null) {
return (string) $raw;
}
$clients = $this->clientRepository->findAll(Pagination::ofOffsetAndLimit(0, 50));
$items = $clients->getItems();
if ($items === []) {
$this->error('No clients found in the database.');
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);
}
/**
* @throws \InvalidArgumentException
*/
private function parseClientIdentifier(string $value): ClientIdentifier
{
try {
return new ClientIdentifier($value);
} catch (\InvalidArgumentException) {
throw new \InvalidArgumentException("Invalid client identifier '{$value}'. Expected a valid client identifier.");
}
}
private function resolveDesiredStatus(ClientIdentifier $clientIdentifier): bool
{
$status = $this->argument('status') !== null ? (string) $this->argument('status') : null;
return match ($status) {
'activate' => true,
'deactivate' => false,
null => $this->resolveToggledStatus($clientIdentifier),
default => throw new \InvalidArgumentException("Invalid status '{$status}'. Expected 'activate' or 'deactivate'."),
};
}
private function resolveToggledStatus(ClientIdentifier $clientIdentifier): bool
{
$client = $this->clientRepository->findByIdentifier($clientIdentifier)
?? throw ClientNotFoundException::forClient($clientIdentifier->value);
return ! $client->isActive;
}
}

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Presentation\Console\Presenters\Clients;
use Application\Security\Usecases\ToggleClientStatus\Output;
use Shared\DDD\Usecase\Output as UsecaseOutput;
use Shared\DDD\Usecase\Presenter;
use Webmozart\Assert\Assert;
/** @implements Presenter<Output, ToggleClientStatusView> */
final readonly class SetClientStatusPresenter implements Presenter
{
#[\Override]
public function present(UsecaseOutput $output): object
{
Assert::isInstanceOf($output, Output::class);
$statusLabel = $output->isActive ? 'Active' : 'Inactive';
$message = "Client '{$output->clientName->value}' (ID: {$output->clientId->value}) is now {$statusLabel}.";
return new ToggleClientStatusView(
id: $output->clientId->value,
name: $output->clientName->value,
identifier: $output->clientIdentifier->value,
isActive: $output->isActive,
statusLabel: $statusLabel,
message: $message,
);
}
}

View file

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

View file

@ -11,23 +11,26 @@ use Ramsey\Uuid\Uuid;
covers(ListClientsCommand::class);
describe('ListClientsCommand', function (): void {
it('outputs message when no clients exist', function (): void {
it('outputs no clients found when database is empty', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
ApiClient::query()->delete();
// WHEN & THEN
// WHEN
$this->artisan('client:list')
// THEN
->expectsOutput('No clients found.')
->assertSuccessful();
});
it('lists clients in a table when clients exist', function (): void {
it('outputs table of clients when clients exist', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
ApiClient::query()->delete();
$client1 = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Gateway Alpha',
'name' => 'Production Gateway',
'identifier' => 'arcadia_id_' . str_repeat('a', 32),
'secret' => 'arcadia_sec_' . str_repeat('b', 86),
'is_active' => true,
@ -35,23 +38,23 @@ describe('ListClientsCommand', function (): void {
$client2 = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Gateway Beta',
'name' => 'Backup Gateway',
'identifier' => 'arcadia_id_' . str_repeat('c', 32),
'secret' => 'arcadia_sec_' . str_repeat('d', 86),
'is_active' => false,
]);
// WHEN & THEN
// WHEN
$this->artisan('client:list')
// THEN
->expectsTable(
['ID', 'Name', 'Identifier', 'Status', 'Created At', 'Updated At'],
['ID', 'Name', 'Identifier', 'Status', 'Last Updated At'],
[
[
(string) $client1->id,
(string) $client1->name->value,
(string) $client1->identifier->value,
'Active',
$client1->created_at->format('Y-m-d H:i:s'),
$client1->updated_at->format('Y-m-d H:i:s'),
],
[
@ -59,7 +62,6 @@ describe('ListClientsCommand', function (): void {
(string) $client2->name->value,
(string) $client2->identifier->value,
'Inactive',
$client2->created_at->format('Y-m-d H:i:s'),
$client2->updated_at->format('Y-m-d H:i:s'),
],
]
@ -70,6 +72,7 @@ describe('ListClientsCommand', function (): void {
it('respects pagination options', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
ApiClient::query()->delete();
for ($i = 1; $i <= 3; $i++) {
@ -82,8 +85,9 @@ describe('ListClientsCommand', function (): void {
]);
}
// WHEN & THEN
// WHEN
$this->artisan('client:list', ['--page' => '2', '--per-page' => '2'])
// THEN
->expectsOutput('Showing page 2/2 (Total: 3 client(s))')
->assertSuccessful();
});

View file

@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Console\Commands;
use Infra\Database\Models\ApiClient;
use Presentation\Console\Commands\ToggleClientStatusCommand;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Console\Tester\CommandCompletionTester;
covers(ToggleClientStatusCommand::class);
describe('ToggleClientStatusCommand', function (): void {
it('errors when an invalid identifier is provided', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$invalidId = 'not-a-valid-identifier';
// WHEN
$this->artisan('client:toggle-status', ['identifier' => $invalidId])
// THEN
->expectsOutput("Invalid client identifier '{$invalidId}'. Expected a valid client identifier.")
->assertFailed();
});
it('errors when client does not exist', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$nonExistentId = 'arcadia_id_' . str_repeat('9', 32);
// WHEN
$this->artisan('client:toggle-status', ['identifier' => $nonExistentId])
// THEN
->expectsOutput("Client '{$nonExistentId}' not found.")
->assertFailed();
});
it('toggles an active client to inactive when no status argument is passed', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$client = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Production Gateway',
'identifier' => 'arcadia_id_' . str_repeat('a', 32),
'secret' => 'arcadia_sec_' . str_repeat('b', 86),
'is_active' => true,
]);
// WHEN
$this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value])
// THEN
->expectsOutput("Client 'Production Gateway' (ID: {$client->id}) is now Inactive.")
->assertSuccessful();
$client->refresh();
expect($client->is_active)->toBeFalse();
});
it('toggles an inactive client to active when no status argument is passed', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$client = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Backup Gateway',
'identifier' => 'arcadia_id_' . str_repeat('c', 32),
'secret' => 'arcadia_sec_' . str_repeat('d', 86),
'is_active' => false,
]);
// WHEN
$this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value])
// THEN
->expectsOutput("Client 'Backup Gateway' (ID: {$client->id}) is now Active.")
->assertSuccessful();
$client->refresh();
expect($client->is_active)->toBeTrue();
});
it('activates an inactive client when activate status is passed', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$client = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Special Gateway',
'identifier' => 'arcadia_id_' . str_repeat('e', 32),
'secret' => 'arcadia_sec_' . str_repeat('f', 86),
'is_active' => false,
]);
// WHEN
$this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value, 'status' => 'activate'])
// THEN
->expectsOutput("Client 'Special Gateway' (ID: {$client->id}) is now Active.")
->assertSuccessful();
$client->refresh();
expect($client->is_active)->toBeTrue();
});
it('deactivates an active client when deactivate status is passed', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$client = ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Special Gateway',
'identifier' => 'arcadia_id_' . str_repeat('g', 32),
'secret' => 'arcadia_sec_' . str_repeat('h', 86),
'is_active' => true,
]);
// WHEN
$this->artisan('client:toggle-status', ['identifier' => (string) $client->identifier->value, 'status' => 'deactivate'])
// THEN
->expectsOutput("Client 'Special Gateway' (ID: {$client->id}) is now Inactive.")
->assertSuccessful();
$client->refresh();
expect($client->is_active)->toBeFalse();
});
it('errors when an invalid status is passed', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
$identifier = 'arcadia_id_' . str_repeat('z', 32);
ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Some Gateway',
'identifier' => $identifier,
'secret' => 'arcadia_sec_' . str_repeat('z', 86),
'is_active' => true,
]);
// WHEN
$this->artisan('client:toggle-status', ['identifier' => $identifier, 'status' => 'unknown'])
// THEN
->expectsOutput("Invalid status 'unknown'. Expected 'activate' or 'deactivate'.")
->assertFailed();
});
it('provides autocompletion suggestions for identifier', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
ApiClient::query()->delete();
ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Production Gateway',
'identifier' => 'arcadia_id_' . str_repeat('a', 32),
'secret' => 'arcadia_sec_' . str_repeat('b', 86),
'is_active' => true,
]);
ApiClient::query()->create([
'id' => (string) Uuid::uuid7(),
'name' => 'Backup Gateway',
'identifier' => 'arcadia_id_' . str_repeat('c', 32),
'secret' => 'arcadia_sec_' . str_repeat('d', 86),
'is_active' => false,
]);
/** @var ToggleClientStatusCommand $command */
$command = app(ToggleClientStatusCommand::class);
$tester = new CommandCompletionTester($command);
// WHEN
$suggestions = $tester->complete(['']);
// THEN
expect($suggestions)
->toContain('arcadia_id_' . str_repeat('a', 32))
->toContain('arcadia_id_' . str_repeat('c', 32));
});
it('provides autocompletion suggestions for status argument', function (): void {
// GIVEN
/** @var \Tests\TestCase $this */
/** @var ToggleClientStatusCommand $command */
$command = app(ToggleClientStatusCommand::class);
$tester = new CommandCompletionTester($command);
$someId = 'arcadia_id_' . str_repeat('1', 32);
// WHEN
$suggestions = $tester->complete([$someId, '']);
// THEN
expect($suggestions)
->toContain('activate')
->toContain('deactivate');
});
});

View file

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Tests\Integration\Infra\Adapters\Events;
use Illuminate\Contracts\Events\Dispatcher;
use Infra\Adapters\Events\LaravelDomainEventDispatcher;
use Mockery;
use Shared\DDD\Event\Event;
covers(LaravelDomainEventDispatcher::class);
describe('LaravelDomainEventDispatcher Integration Tests', function (): void {
it('dispatches domain events to Laravel event dispatcher', function (): void {
// GIVEN
$laravelDispatcher = Mockery::mock(Dispatcher::class);
$dispatcher = new LaravelDomainEventDispatcher($laravelDispatcher);
$event = new class () implements Event
{
};
$laravelDispatcher->expects('dispatch')
->once()
->with($event);
// WHEN
$dispatcher->dispatch($event);
// THEN
expect(true)->toBeTrue();
});
});

View file

@ -13,33 +13,33 @@ use Application\Security\Models\ValueObjects\ClientSecret;
use Application\Security\Models\ValueObjects\Entities\ClientId;
use Application\Security\Usecases\ToggleClientStatus\Input;
use Application\Security\Usecases\ToggleClientStatus\Output;
use Application\Security\Usecases\ToggleClientStatus\ToggleClientStatus;
use Application\Security\Usecases\ToggleClientStatus\SetClientStatus;
use Infra\Adapters\Repositories\InMemoryClientRepository;
use Mockery;
use Ramsey\Uuid\Uuid;
use Shared\DDD\Event\DomainEventDispatcher;
covers(
ToggleClientStatus::class,
SetClientStatus::class,
Input::class,
Output::class,
);
describe('ToggleClientStatus Usecase Unit Tests', function (): void {
describe('SetClientStatus Usecase', function (): void {
$repository = new InMemoryClientRepository();
beforeEach(function () use ($repository): void {
$repository->clear();
});
it('toggles an active client to inactive and dispatches event', function () use ($repository): void {
it('deactivates an active client and dispatches event', function () use ($repository): void {
// GIVEN
$dispatcher = Mockery::mock(DomainEventDispatcher::class);
$usecase = new ToggleClientStatus($repository, $dispatcher);
$usecase = new SetClientStatus($repository, $dispatcher);
$clientId = new ClientId(Uuid::uuid7());
$identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32));
$name = new ClientName('Test Gateway');
$name = new ClientName('Test Gateway 1');
$secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86));
$client = Client::hydrate(
@ -60,7 +60,7 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void {
&& $event->clientId->equals($clientId)
&& $event->isActive === false);
$input = new Input($clientId);
$input = new Input($identifier, desiredStatus: false);
// WHEN
$result = $usecase->execute($input);
@ -76,10 +76,10 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void {
expect($saved?->isActive)->toBeFalse();
});
it('toggles an inactive client to active and dispatches event', function () use ($repository): void {
it('activates an inactive client and dispatches event', function () use ($repository): void {
// GIVEN
$dispatcher = Mockery::mock(DomainEventDispatcher::class);
$usecase = new ToggleClientStatus($repository, $dispatcher);
$usecase = new SetClientStatus($repository, $dispatcher);
$clientId = new ClientId(Uuid::uuid7());
$identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32));
@ -104,7 +104,7 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void {
&& $event->clientId->equals($clientId)
&& $event->isActive === true);
$input = new Input($clientId);
$input = new Input($identifier, desiredStatus: true);
// WHEN
$result = $usecase->execute($input);
@ -120,13 +120,132 @@ describe('ToggleClientStatus Usecase Unit Tests', function (): void {
it('throws ClientNotFoundException when client does not exist', function () use ($repository): void {
// GIVEN
$dispatcher = Mockery::mock(DomainEventDispatcher::class);
$usecase = new ToggleClientStatus($repository, $dispatcher);
$usecase = new SetClientStatus($repository, $dispatcher);
$clientId = new ClientId(Uuid::uuid7());
$input = new Input($clientId);
$identifier = new ClientIdentifier('arcadia_id_' . str_repeat('9', 32));
$input = new Input($identifier, desiredStatus: true);
// WHEN & THEN
expect(fn () => $usecase->execute($input))
->toThrow(ClientNotFoundException::class);
});
it('does not dispatch event when status is already the desired value', function () use ($repository): void {
// GIVEN
$dispatcher = Mockery::mock(DomainEventDispatcher::class);
$usecase = new SetClientStatus($repository, $dispatcher);
$clientId = new ClientId(Uuid::uuid7());
$identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32));
$name = new ClientName('Already Active Client');
$secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86));
$client = Client::hydrate(
id: $clientId,
name: $name,
identifier: $identifier,
secret: $secret,
isActive: true,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
);
$repository->add($client);
$dispatcher->expects('dispatch')->never();
$input = new Input($identifier, desiredStatus: true);
// WHEN
$result = $usecase->execute($input);
// THEN
expect($result)->toBeInstanceOf(Output::class)
->and($result->isActive)->toBeTrue();
$saved = $repository->find($clientId);
expect($saved?->isActive)->toBeTrue();
});
it('deactivates an active client when desiredStatus is false', function () use ($repository): void {
// GIVEN
$dispatcher = Mockery::mock(DomainEventDispatcher::class);
$usecase = new SetClientStatus($repository, $dispatcher);
$clientId = new ClientId(Uuid::uuid7());
$identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32));
$name = new ClientName('Test Gateway 3');
$secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86));
$client = Client::hydrate(
id: $clientId,
name: $name,
identifier: $identifier,
secret: $secret,
isActive: true,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
);
$repository->add($client);
$dispatcher->expects('dispatch')
->once()
->withArgs(fn ($event): bool => $event instanceof ClientStatusToggled
&& $event->clientId->equals($clientId)
&& $event->isActive === false);
$input = new Input($identifier, desiredStatus: false);
// WHEN
$result = $usecase->execute($input);
// THEN
expect($result)->toBeInstanceOf(Output::class)
->and($result->isActive)->toBeFalse();
$saved = $repository->find($clientId);
expect($saved?->isActive)->toBeFalse();
});
it('activates an inactive client when desiredStatus is true', function () use ($repository): void {
// GIVEN
$dispatcher = Mockery::mock(DomainEventDispatcher::class);
$usecase = new SetClientStatus($repository, $dispatcher);
$clientId = new ClientId(Uuid::uuid7());
$identifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32));
$name = new ClientName('Test Gateway 2');
$secret = new ClientSecret('arcadia_sec_' . str_repeat('b', 86));
$client = Client::hydrate(
id: $clientId,
name: $name,
identifier: $identifier,
secret: $secret,
isActive: false,
createdAt: new \DateTimeImmutable(),
updatedAt: new \DateTimeImmutable(),
);
$repository->add($client);
$dispatcher->expects('dispatch')
->once()
->withArgs(fn ($event): bool => $event instanceof ClientStatusToggled
&& $event->clientId->equals($clientId)
&& $event->isActive === true);
$input = new Input($identifier, desiredStatus: true);
// WHEN
$result = $usecase->execute($input);
// THEN
expect($result)->toBeInstanceOf(Output::class)
->and($result->isActive)->toBeTrue();
$saved = $repository->find($clientId);
expect($saved?->isActive)->toBeTrue();
});
});