From 582f111e9d510e47daeb8d0736351eb99787c020 Mon Sep 17 00:00:00 2001 From: beau-dev Date: Wed, 27 Nov 2024 20:35:36 +0100 Subject: [PATCH] improved StringRecord class - StringRecordId constructor accepts now `StringRecordId` or `RecordId` as argument --- src/Cbor/Types/Record/StringRecordId.php | 11 ++++++-- tests/core/cbor/StringRecordIdTest.php | 35 +++++++++++++++++++++++- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/Cbor/Types/Record/StringRecordId.php b/src/Cbor/Types/Record/StringRecordId.php index 81d4d9e..77fd576 100644 --- a/src/Cbor/Types/Record/StringRecordId.php +++ b/src/Cbor/Types/Record/StringRecordId.php @@ -6,11 +6,16 @@ final readonly class StringRecordId implements RecordInterface { + /** @var string $recordId */ public string $recordId; - public function __construct(string $recordId) + public function __construct(string|StringRecordId|RecordId $recordId) { - $this->recordId = $recordId; + $this->recordId = match(true) { + $recordId instanceof StringRecordId => $recordId->toString(), + $recordId instanceof RecordId => $recordId->toString(), + default => $recordId + }; } public function __toString(): string @@ -30,7 +35,7 @@ public function jsonSerialize(): string public function equals(StringRecordId $recordId): bool { - return $this->recordId === $recordId->recordId; + return $this->recordId === $recordId->toString(); } public static function create(string $recordId): StringRecordId diff --git a/tests/core/cbor/StringRecordIdTest.php b/tests/core/cbor/StringRecordIdTest.php index 7bb3435..48368e2 100644 --- a/tests/core/cbor/StringRecordIdTest.php +++ b/tests/core/cbor/StringRecordIdTest.php @@ -1,10 +1,11 @@ assertEquals(self::RECORD_ID_STRING, strval($stringRecordId)); } + + public function testInstantiateStringRecordId() + { + $stringRecordId = new StringRecordId(self::RECORD_ID_STRING); + $this->assertEquals(self::RECORD_ID_STRING, $stringRecordId->toString()); + } + + public function testEquals() + { + $strid1 = new StringRecordId(self::RECORD_ID_STRING); + $strid2 = new StringRecordId(self::RECORD_ID_STRING); + + $this->assertTrue($strid1->equals($strid2)); + + $strid3 = new StringRecordId("record:some-other-record-1"); + $this->assertFalse($strid1->equals($strid3)); + } + + public function testJSONSerialize() + { + $strid = new StringRecordId(self::RECORD_ID_STRING); + $this->assertEquals('"' . self::RECORD_ID_STRING . '"', json_encode($strid)); + + // reparsing the JSON should give the same string + $this->assertEquals(self::RECORD_ID_STRING, json_decode(json_encode($strid), true)); + } + + public function testCreate() + { + $strid = StringRecordId::create(self::RECORD_ID_STRING); + $this->assertEquals(self::RECORD_ID_STRING, $strid->toString()); + } } \ No newline at end of file