fix(shared): prevent cross-type equality in EntityId::equals (LSP)

This commit is contained in:
Jérémy Munsch 2026-08-20 09:45:54 +02:00
parent 98356465d5
commit 2bbfc7fa08
Signed by: forge-joniko
GPG key ID: D7EFE2F5CB6CC0E4
2 changed files with 25 additions and 1 deletions

View file

@ -23,6 +23,6 @@ abstract readonly class EntityId implements \Stringable, Equatable
#[\Override]
public function equals(mixed $other): bool
{
return $other instanceof self && $this->value === $other->value;
return $other instanceof static && $this->value === $other->value;
}
}

View file

@ -33,4 +33,28 @@ describe('EntityId', function (): void {
{
})->toThrow(\DomainException::class);
});
it('correctly compares equality for identical and distinct instances', function (): void {
// GIVEN
$classA1 = new DummyEntityIdA('uuid-1');
$classA2 = new DummyEntityIdA('uuid-1');
$classA3 = new DummyEntityIdA('uuid-2');
$classB = new DummyEntityIdB('uuid-1');
// WHEN & THEN
expect($classA1->equals($classA2))->toBeTrue()
->and($classA1->equals($classA3))->toBeFalse()
->and($classA1->equals($classB))->toBeFalse()
->and($classB->equals($classA1))->toBeFalse()
->and($classA1->equals('uuid-1'))->toBeFalse()
->and($classA1->equals(null))->toBeFalse();
});
});
final readonly class DummyEntityIdA extends EntityId
{
}
final readonly class DummyEntityIdB extends EntityId
{
}