diff --git a/src/Symfony/Component/Uid/AbstractUid.php b/src/Symfony/Component/Uid/AbstractUid.php index b65fa44f5b551..debc73af2e9e3 100644 --- a/src/Symfony/Component/Uid/AbstractUid.php +++ b/src/Symfony/Component/Uid/AbstractUid.php @@ -14,7 +14,7 @@ /** * @author Nicolas Grekas */ -abstract class AbstractUid implements \JsonSerializable, \Stringable +abstract class AbstractUid implements \JsonSerializable, \Stringable, HashableInterface { /** * The identifier in its canonic representation. @@ -159,6 +159,11 @@ public function equals(mixed $other): bool return $this->uid === $other->uid; } + public function hash(): string + { + return $this->uid; + } + public function compare(self $other): int { return (\strlen($this->uid) - \strlen($other->uid)) ?: ($this->uid <=> $other->uid); diff --git a/src/Symfony/Component/Uid/CHANGELOG.md b/src/Symfony/Component/Uid/CHANGELOG.md index 8fea6eb6ecbf9..73cde81e3413b 100644 --- a/src/Symfony/Component/Uid/CHANGELOG.md +++ b/src/Symfony/Component/Uid/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +7.2 +--- + + * Make `AbstractUid` implement `Ds\Hashable` if available + 7.1 --- diff --git a/src/Symfony/Component/Uid/HashableInterface.php b/src/Symfony/Component/Uid/HashableInterface.php new file mode 100644 index 0000000000000..8a2787fb93f0e --- /dev/null +++ b/src/Symfony/Component/Uid/HashableInterface.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Uid; + +if (interface_exists(\Ds\Hashable::class)) { + /** + * @internal + */ + interface HashableInterface extends \Ds\Hashable + { + public function hash(): string; + } +} else { + /** + * @internal + */ + interface HashableInterface + { + public function equals(mixed $other): bool; + + public function hash(): string; + } +} diff --git a/src/Symfony/Component/Uid/Tests/UuidTest.php b/src/Symfony/Component/Uid/Tests/UuidTest.php index 834fb5d26dd83..ab1761aac1830 100644 --- a/src/Symfony/Component/Uid/Tests/UuidTest.php +++ b/src/Symfony/Component/Uid/Tests/UuidTest.php @@ -248,6 +248,29 @@ public static function provideInvalidEqualType(): iterable yield [new \stdClass()]; } + public function testHashable() + { + $uuid1 = new UuidV4(self::A_UUID_V4); + $uuid2 = new UuidV4(self::A_UUID_V4); + + $this->assertSame($uuid1->hash(), $uuid2->hash()); + } + + /** @requires extension ds */ + public function testDsCompatibility() + { + $uuid1 = new UuidV4(self::A_UUID_V4); + $uuid2 = new UuidV4(self::A_UUID_V4); + + $set = new \Ds\Set(); + $set->add($uuid1); + $set->add($uuid2); + + $this->assertTrue($set->contains($uuid1)); + $this->assertTrue($set->contains($uuid2)); + $this->assertCount(1, $set); + } + public function testCompare() { $uuids = [];