diff --git a/CHANGELOG.md b/CHANGELOG.md index 29bb07b5..121f31ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ All notable changes to this project will be documented in this file. This projec ## Unreleased +### Added + +- New `IsEntityWithTypedId` trait for use on entities that strictly type their id. + ## [6.0.1] - 2026-06-13 ### Fixed diff --git a/src/Domain/IsEntityWithTypedId.php b/src/Domain/IsEntityWithTypedId.php new file mode 100644 index 00000000..bf648819 --- /dev/null +++ b/src/Domain/IsEntityWithTypedId.php @@ -0,0 +1,45 @@ +id; + } + + public function getIdOrFail(): Identifier + { + return $this->id; + } + + public function is(?Entity $other): bool + { + if ($other instanceof $this) { + return $this->id->is( + $other->getId(), + ); + } + + return false; + } + + public function isNot(?Entity $other): bool + { + return !$this->is($other); + } +} diff --git a/tests/Unit/Domain/EntityWithTypedIdTest.php b/tests/Unit/Domain/EntityWithTypedIdTest.php new file mode 100644 index 00000000..799b409a --- /dev/null +++ b/tests/Unit/Domain/EntityWithTypedIdTest.php @@ -0,0 +1,89 @@ +assertSame($id, $entity->id); + $this->assertSame($id, $entity->getId()); + $this->assertSame($id, $entity->getIdOrFail()); + $this->assertFalse($entity->is(null)); + $this->assertTrue($entity->isNot(null)); + } + + public function testItIsTheSame(): void + { + $a = new TestEntityWithTypedId( + $id1 = UuidV7::make(), + ); + + $b = new TestEntityWithTypedId( + UuidV7::from($id1->toString()), + ); + + $this->assertTrue($a->is($b)); + $this->assertFalse($a->isNot($b)); + } + + public function testItIsNotTheSame(): void + { + $a = new TestEntityWithTypedId(UuidV7::make()); + $b = new TestEntityWithTypedId(UuidV7::make()); + + $this->assertFalse($a->is($b)); + $this->assertTrue($a->isNot($b)); + } + + public function testItIsDifferentClass(): void + { + $a = new TestEntityWithTypedId(UuidV7::make()); + $b = $this->createMock(Entity::class); + $b->method('getId')->willReturn(UuidV7::from($a->id->toString())); + + $this->assertFalse($a->is($b)); + $this->assertTrue($a->isNot($b)); + } + + public function testItCanUseTraitOnNonReadonlyClass(): void + { + $id = new IntegerId(123); + + $entity = new class ($id, 'Bob') implements Entity { + use IsEntityWithTypedId; + + public function __construct(public IntegerId $id, public private(set) string $name) + { + } + + public function changeName(string $name): void + { + $this->name = $name; + } + }; + + $this->assertSame($id, $entity->getId()); + $this->assertSame('Bob', $entity->name); + $entity->changeName('Chris'); + $this->assertSame('Chris', $entity->name); + } +} diff --git a/tests/Unit/Domain/TestEntityWithTypedId.php b/tests/Unit/Domain/TestEntityWithTypedId.php new file mode 100644 index 00000000..00c70a7c --- /dev/null +++ b/tests/Unit/Domain/TestEntityWithTypedId.php @@ -0,0 +1,26 @@ +