Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,22 @@ All notable changes to this project will be documented in this file. This projec

## Unreleased

### Fixed

- `EnqueuerContainer::bind()` now throws an `InfrastructureException` when given a string binding without a PSR
container, instead of failing later when the enqueuer is resolved.
- `KeyedSetOfErrors::put()` and `merge()` now sort keys case-insensitively, matching the constructor.
- `Meta::merge()` no longer renumbers numeric string keys.
- `Error` now accepts a message of `'0'` and no longer converts a key of `'0'` to `null`.
- The `ContractException` thrown by `UuidV4` and `UuidV7` when given a lazy UUID of the wrong version now has a message.
- `FakeExceptionReporter` now rethrows when more exceptions have already been reported than expected, e.g. when
`none()` is called after an exception was reported.
- `FakeLogger::messages()` no longer drops a message of `'0'`.
- `LogPushedToQueue` now implements the `QueueMiddleware` interface, instead of `CommandMiddleware`. Its `__invoke()`
method now has a `void` return type, matching the queue middleware contract.
- `FakeContainer` now allows the built-in exception reporter, logger and unit of work services to be overridden via
`bind()` or `instance()`. Its `has()` method also no longer resolves the binding to check if it exists.

## [6.1.0] - 2026-11-14

### Added
Expand Down
6 changes: 6 additions & 0 deletions src/Infrastructure/Queue/EnqueuerContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ public function __construct(
*/
public function bind(array|string $queueableName, Closure|string $binding): void
{
if (is_string($binding) && $this->container === null) {
throw new InfrastructureException(
'Cannot bind enqueuer as a string without a PSR container.',
);
}

if (is_string($queueableName)) {
$queueableName = [$queueableName];
}
Expand Down
8 changes: 3 additions & 5 deletions src/Infrastructure/Queue/Middleware/LogPushedToQueue.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@

use Closure;
use CloudCreativity\Modules\Bus\SanitizedMessage;
use CloudCreativity\Modules\Contracts\Bus\Middleware\CommandMiddleware;
use CloudCreativity\Modules\Contracts\Infrastructure\Queue\QueueMiddleware;
use CloudCreativity\Modules\Contracts\Messaging\Command;
use CloudCreativity\Modules\Toolkit\ModuleBasename;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

final readonly class LogPushedToQueue implements CommandMiddleware
final readonly class LogPushedToQueue implements QueueMiddleware
{
public function __construct(
private LoggerInterface $log,
Expand All @@ -29,7 +29,7 @@ public function __construct(
) {
}

public function __invoke(Command $command, Closure $next): null
public function __invoke(Command $command, Closure $next): void
{
$name = ModuleBasename::tryFrom($command)?->toString() ?? $command::class;

Expand All @@ -42,7 +42,5 @@ public function __invoke(Command $command, Closure $next): null
$next($command);

$this->log->log($this->queuedLevel, "Queued command {$name}.", $context);

return null;
}
}
26 changes: 11 additions & 15 deletions src/Testing/FakeContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,29 +50,25 @@ public function instance(string $id, mixed $instance): void

public function get(string $id)
{
$stub = match ($id) {
if (isset($this->bindings[$id])) {
return $this->bindings[$id]() ?? $this->abort($id);
}

return match ($id) {
ExceptionReporter::class => $this->reporter,
LoggerInterface::class => $this->logger,
UnitOfWork::class => $this->unitOfWork,
default => null,
default => $this->abort($id),
};

if ($stub === null) {
$binding = $this->bindings[$id] ?? null;
$stub = $binding ? $binding() : null;
}

return $stub ?? $this->abort($id);
}

public function has(string $id): bool
{
try {
$this->get($id);
return true;
} catch (NotFoundExceptionInterface) {
return false;
}
return isset($this->bindings[$id]) || in_array($id, [
ExceptionReporter::class,
LoggerInterface::class,
UnitOfWork::class,
], true);
}

protected function abort(string $id): never
Expand Down
2 changes: 1 addition & 1 deletion src/Testing/FakeExceptionReporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ final class FakeExceptionReporter implements ExceptionReporter, Countable, Array

public function report(Throwable $ex): void
{
if ($this->expected === count($this->reported)) {
if ($this->expected !== null && count($this->reported) >= $this->expected) {
throw $ex;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Testing/FakeLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function messages(): array
fn (array $entry): string => implode(': ', array_filter([
is_scalar($entry['level']) ? strtoupper((string) $entry['level']) : null,
$entry['message'],
])),
], static fn (?string $value): bool => $value !== null)),
$this->log,
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Toolkit/Identifiers/UuidV4.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public static function tryFrom(IBaseUuid|Identifier|string|null $value): ?self
public function __construct(public readonly BaseUuidV4|LazyUuidFromString $value)
{
if ($this->value instanceof LazyUuidFromString) {
Contracts::assert($this->value->getVersion() === 4);
Contracts::assert($this->value->getVersion() === 4, 'Expecting a version 4 UUID.');
}
}
}
2 changes: 1 addition & 1 deletion src/Toolkit/Identifiers/UuidV7.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static function tryFrom(IBaseUuid|Identifier|string|null $value): ?self
public function __construct(public readonly BaseUuidV7|LazyUuidFromString $value)
{
if ($this->value instanceof LazyUuidFromString) {
Contracts::assert($this->value->getVersion() === 7);
Contracts::assert($this->value->getVersion() === 7, 'Expecting a version 7 UUID.');
}
}
}
4 changes: 2 additions & 2 deletions src/Toolkit/Result/Error.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public function __construct(
private string $message = '',
string|UnitEnum|null $key = null,
) {
Contracts::assert(!empty($message) || $code !== null, 'Error must have a message or a code.');
$this->key = $key ?: null;
Contracts::assert($message !== '' || $code !== null, 'Error must have a message or a code.');
$this->key = $key === '' ? null : $key;
}

public function key(): string|UnitEnum|null
Expand Down
11 changes: 8 additions & 3 deletions src/Toolkit/Result/KeyedSetOfErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function __construct(IError ...$errors)
$this->stack[$key] = $this->get($key)->push($error);
}

ksort($this->stack, SORT_STRING | SORT_FLAG_CASE);
$this->sort();
}

/**
Expand All @@ -63,7 +63,7 @@ public function put(IError $error): self
$copy = clone $this;
$copy->stack[$key] = $errors->push($error);

ksort($copy->stack);
$copy->sort();

return $copy;
}
Expand All @@ -76,7 +76,7 @@ public function merge(IListOfErrors|self $other): self
$copy->stack[$key] = $copy->get($key)->merge($errors);
}

ksort($copy->stack);
$copy->sort();

return $copy;
}
Expand Down Expand Up @@ -126,6 +126,11 @@ public function count(): int
return $count;
}

private function sort(): void
{
ksort($this->stack, SORT_STRING | SORT_FLAG_CASE);
}

private function keyFor(IError $error): string
{
$key = $error->key();
Expand Down
2 changes: 1 addition & 1 deletion src/Toolkit/Result/Meta.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public function merge(array|self $values): self
}

$copy = clone $this;
$copy->stack = array_merge($this->stack, $values);
$copy->stack = array_replace($this->stack, $values);

return $copy;
}
Expand Down
11 changes: 11 additions & 0 deletions tests/Unit/Infrastructure/Queue/EnqueuerContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,15 @@ public function it_throws_when_setting_a_string_default_enqueuer_without_a_psr_c

$container->withDefault(TestEnqueuer::class);
}

#[Test]
public function it_throws_when_binding_a_string_enqueuer_without_a_psr_container(): void
{
$container = new EnqueuerContainer();

$this->expectException(InfrastructureException::class);
$this->expectExceptionMessage('Cannot bind enqueuer as a string without a PSR container.');

$container->bind(TestQueueableCommand::class, TestEnqueuer::class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@

namespace CloudCreativity\Modules\Tests\Unit\Infrastructure\Queue\Middleware;

use CloudCreativity\Modules\Contracts\Infrastructure\Queue\QueueMiddleware;
use CloudCreativity\Modules\Contracts\Messaging\Command;
use CloudCreativity\Modules\Infrastructure\Queue\Middleware\LogPushedToQueue;
use CloudCreativity\Modules\Testing\FakeLogger;
use CloudCreativity\Modules\Tests\Unit\Infrastructure\Queue\TestQueueableCommand;
use CloudCreativity\Modules\Toolkit\Result\Result;
use LogicException;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
Expand All @@ -42,15 +42,22 @@ protected function tearDown(): void
parent::tearDown();
}

#[Test]
public function it_is_queue_middleware(): void
{
$middleware = new LogPushedToQueue($this->logger);

$this->assertInstanceOf(QueueMiddleware::class, $middleware);
}

#[Test]
public function it_logs_with_the_default_levels(): void
{
$passed = null;
$middleware = new LogPushedToQueue($this->logger);

$middleware($this->command, function (Command $command) use (&$passed): Result {
$middleware($this->command, function (Command $command) use (&$passed): void {
$passed = $command;
return Result::ok();
});

$context = ['command' => ['name' => 'bar']];
Expand All @@ -67,7 +74,8 @@ public function it_logs_with_custom_levels(): void
{
$middleware = new LogPushedToQueue($this->logger, LogLevel::NOTICE, LogLevel::WARNING);

$middleware($this->command, fn (): Result => Result::ok());
$middleware($this->command, static function (): void {
});

$this->assertSame([
'NOTICE: Queuing command Tests:TestQueueableCommand.',
Expand All @@ -82,7 +90,8 @@ public function it_uses_the_fully_qualified_class_name_when_there_is_no_module_b
$name = $command::class;
$middleware = new LogPushedToQueue($this->logger);

$middleware($command, fn (): Result => Result::ok());
$middleware($command, static function (): void {
});

$this->assertSame([
"DEBUG: Queuing command {$name}.",
Expand All @@ -96,9 +105,8 @@ public function it_logs_before_the_next_closure_is_invoked(): void
$messages = null;
$middleware = new LogPushedToQueue($this->logger);

$middleware($this->command, function () use (&$messages): Result {
$middleware($this->command, function () use (&$messages): void {
$messages = $this->logger->messages();
return Result::ok();
});

$this->assertSame(['DEBUG: Queuing command Tests:TestQueueableCommand.'], $messages);
Expand Down
30 changes: 30 additions & 0 deletions tests/Unit/Testing/FakeContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,21 @@ public function it_resolves_the_unit_of_work(): void
$this->assertSame($this->container->unitOfWork, $actual);
}

/**
* @param class-string $id
*/
#[DataProvider('builtInServiceProvider')]
#[Test]
public function it_resolves_a_binding_that_overrides_a_built_in_service(string $id): void
{
$instance = new stdClass();
$this->container->instance($id, $instance);

$actual = $this->container->get($id);

$this->assertSame($instance, $actual);
}

#[Test]
public function it_resolves_a_binding_each_time_it_is_requested(): void
{
Expand Down Expand Up @@ -201,4 +216,19 @@ public function it_does_not_have_an_unknown_service(): void

$this->assertFalse($actual);
}

#[Test]
public function it_does_not_resolve_a_binding_when_checking_if_it_exists(): void
{
$resolved = false;
$this->container->bind('foo', function () use (&$resolved): string {
$resolved = true;
return 'bar';
});

$actual = $this->container->has('foo');

$this->assertTrue($actual);
$this->assertFalse($resolved);
}
}
15 changes: 15 additions & 0 deletions tests/Unit/Testing/FakeExceptionReporterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,21 @@ public function it_rethrows_once_the_expected_count_is_reached(): void
$this->reporter->report($expected);
}

#[Test]
public function it_rethrows_when_the_expected_count_has_been_exceeded(): void
{
$expected = new RuntimeException('Boom! That was a surprise.');
$this->reporter->reported = [
new LogicException('Whoops 0!'),
new LogicException('Whoops 1!'),
];
$this->reporter->expect(1);

$this->expectExceptionObject($expected);

$this->reporter->report($expected);
}

// -------------------------------------------------------------------------
// count() and getIterator()
// -------------------------------------------------------------------------
Expand Down
12 changes: 12 additions & 0 deletions tests/Unit/Testing/FakeLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,16 @@ public function it_returns_messages_without_a_prefix_when_the_level_is_not_scala

$this->assertSame(['Some message'], $actual);
}

#[Test]
public function it_returns_a_message_of_zero(): void
{
$this->logger->log = [
['level' => LogLevel::INFO, 'message' => '0', 'context' => []],
];

$actual = $this->logger->messages();

$this->assertSame(['INFO: 0'], $actual);
}
}
1 change: 1 addition & 0 deletions tests/Unit/Toolkit/Identifiers/UuidV4Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public function it_rejects_a_lazy_uuid_of_another_version(): void
$base = new LazyUuidFromString(RamseyUuid::uuid7()->toString());

$this->expectException(ContractException::class);
$this->expectExceptionMessage('Expecting a version 4 UUID.');

new UuidV4($base);
}
Expand Down
1 change: 1 addition & 0 deletions tests/Unit/Toolkit/Identifiers/UuidV7Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ public function it_rejects_a_lazy_uuid_of_another_version(): void
$base = new LazyUuidFromString(RamseyUuid::uuid4()->toString());

$this->expectException(ContractException::class);
$this->expectExceptionMessage('Expecting a version 7 UUID.');

new UuidV7($base);
}
Expand Down
Loading
Loading