Skip to content

Commit b417d14

Browse files
committed
[Uid] Make AbstractUid implement Ds\Hashable if available
1 parent ee7ef2e commit b417d14

File tree

4 files changed

+55
-1
lines changed

4 files changed

+55
-1
lines changed

src/Symfony/Component/Uid/AbstractUid.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,15 @@
1111

1212
namespace Symfony\Component\Uid;
1313

14+
use Ds\Hashable;
15+
16+
// ensure we have _some_ version of the Ds\Hashable interface
17+
require_once __DIR__.'/DsHashablePolyfill.php';
18+
1419
/**
1520
* @author Nicolas Grekas <p@tchwork.com>
1621
*/
17-
abstract class AbstractUid implements \JsonSerializable, \Stringable
22+
abstract class AbstractUid implements \JsonSerializable, \Stringable, Hashable
1823
{
1924
/**
2025
* The identifier in its canonic representation.
@@ -159,6 +164,11 @@ public function equals(mixed $other): bool
159164
return $this->uid === $other->uid;
160165
}
161166

167+
public function hash(): mixed
168+
{
169+
return $this->uid;
170+
}
171+
162172
public function compare(self $other): int
163173
{
164174
return (\strlen($this->uid) - \strlen($other->uid)) ?: ($this->uid <=> $other->uid);

src/Symfony/Component/Uid/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ CHANGELOG
66

77
* Add `UuidV1::toV6()`, `UuidV1::toV7()` and `UuidV6::toV7()`
88
* Add `AbstractUid::toString()`
9+
* Make `AbstractUid` implement `Ds\Hashable` if available
910

1011
6.2
1112
---
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the Symfony package.
7+
*
8+
* (c) Fabien Potencier <fabien@symfony.com>
9+
*
10+
* For the full copyright and license information, please view the LICENSE
11+
* file that was distributed with this source code.
12+
*/
13+
14+
namespace Symfony\Component\Uid;
15+
16+
interface DsHashablePolyfill
17+
{
18+
public function equals(mixed $other): bool;
19+
20+
public function hash(): mixed;
21+
}
22+
23+
if (!interface_exists(\Ds\Hashable::class)) {
24+
class_alias(DsHashablePolyfill::class, \Ds\Hashable::class);
25+
}

src/Symfony/Component/Uid/Tests/UuidTest.php

+18
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,24 @@ public static function provideInvalidEqualType(): iterable
248248
yield [new \stdClass()];
249249
}
250250

251+
public function testHashable()
252+
{
253+
$uuid1 = new UuidV4(self::A_UUID_V4);
254+
$uuid2 = new UuidV4(self::A_UUID_V4);
255+
256+
$this->assertSame($uuid1->hash(), $uuid2->hash());
257+
258+
if (\extension_loaded('ds')) {
259+
$set = new \Ds\Set();
260+
$set->add($uuid1);
261+
$set->add($uuid2);
262+
263+
$this->assertTrue($set->contains($uuid1));
264+
$this->assertTrue($set->contains($uuid2));
265+
$this->assertSame(1, $set->count());
266+
}
267+
}
268+
251269
public function testCompare()
252270
{
253271
$uuids = [];

0 commit comments

Comments
 (0)