From 668b6ab9a2be0323445d8fe6f3874f3c86181c34 Mon Sep 17 00:00:00 2001 From: Ben Ramsey Date: Wed, 8 Jan 2020 20:10:37 -0600 Subject: [PATCH] Use the codec to encode to binary when using Uuid::getBytes() --- src/Codec/GuidStringCodec.php | 10 ++++++++++ src/Codec/StringCodec.php | 2 +- src/Uuid.php | 2 +- tests/Codec/StringCodecTest.php | 2 ++ tests/Encoder/TimestampLastCombCodecTest.php | 3 +++ 5 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/Codec/GuidStringCodec.php b/src/Codec/GuidStringCodec.php index dce190c..48f9ab1 100644 --- a/src/Codec/GuidStringCodec.php +++ b/src/Codec/GuidStringCodec.php @@ -25,6 +25,16 @@ use Ramsey\Uuid\UuidInterface; */ class GuidStringCodec extends StringCodec { + /** + * @psalm-pure + */ + public function encodeBinary(UuidInterface $uuid): string + { + $components = $this->swapBytes($this->extractComponents($uuid->toString())); + + return (string) hex2bin(implode('', $components)); + } + /** * @throws InvalidUuidStringException * diff --git a/src/Codec/StringCodec.php b/src/Codec/StringCodec.php index 0a07d17..be63516 100644 --- a/src/Codec/StringCodec.php +++ b/src/Codec/StringCodec.php @@ -60,7 +60,7 @@ class StringCodec implements CodecInterface */ public function encodeBinary(UuidInterface $uuid): string { - return $uuid->getBytes(); + return (string) hex2bin($uuid->getHex()); } /** diff --git a/src/Uuid.php b/src/Uuid.php index 1fcebd9..96ea639 100644 --- a/src/Uuid.php +++ b/src/Uuid.php @@ -277,7 +277,7 @@ class Uuid implements UuidInterface public function getBytes(): string { - return $this->fields->getBytes(); + return $this->codec->encodeBinary($this); } /** diff --git a/tests/Codec/StringCodecTest.php b/tests/Codec/StringCodecTest.php index 0bff301..174604a 100644 --- a/tests/Codec/StringCodecTest.php +++ b/tests/Codec/StringCodecTest.php @@ -73,6 +73,8 @@ class StringCodecTest extends TestCase public function testEncodeBinaryReturnsBinaryString(): void { $expected = hex2bin('123456781234abcdabef1234abcd4321'); + $this->uuid->method('getHex') + ->willReturn('123456781234abcdabef1234abcd4321'); $this->uuid->method('getBytes') ->willReturn(hex2bin('123456781234abcdabef1234abcd4321')); $codec = new StringCodec($this->builder); diff --git a/tests/Encoder/TimestampLastCombCodecTest.php b/tests/Encoder/TimestampLastCombCodecTest.php index c045dc8..b26275a 100644 --- a/tests/Encoder/TimestampLastCombCodecTest.php +++ b/tests/Encoder/TimestampLastCombCodecTest.php @@ -45,6 +45,9 @@ class TimestampLastCombCodecTest extends TestCase { /** @var MockObject & UuidInterface $uuidMock */ $uuidMock = $this->getMockBuilder(UuidInterface::class)->getMock(); + $uuidMock->expects($this->any()) + ->method('getHex') + ->willReturn('0800200c9a6611e19b21ff6f8cb0c57d'); $uuidMock->expects($this->any()) ->method('getBytes') ->willReturn(hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'));