Skip to content

Commit

Permalink
Merge pull request #23 from teamleadercrm/handle-uuid-exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
pidera authored Jul 3, 2024
2 parents 36f7b58 + 983125f commit 924d842
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "teamleadercrm/uuidifier",
"version": "1.9.0",
"version": "1.9.1",
"require": {
"php": "^8.1",
"ramsey/uuid": ">=4.5 <4.6",
Expand Down
14 changes: 12 additions & 2 deletions src/Uuidifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

namespace Teamleader\Uuidifier;

use InvalidArgumentException;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Exception\UuidExceptionInterface;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\UuidFactory;
use Ramsey\Uuid\UuidInterface;
Expand Down Expand Up @@ -53,6 +53,9 @@ public function encode(string $prefix, int $id): UuidInterface
return $uuidFactory->uuid($bytes);
}

/**
* @throws UuidExceptionInterface
*/
public function decode(UuidInterface $uuid): int
{
if ($uuid->getVersion() !== self::VERSION) {
Expand All @@ -68,7 +71,11 @@ public function decode(UuidInterface $uuid): int
public function isValid(string $prefix, UuidInterface $uuid): bool
{
if ($uuid->getVersion() !== self::VERSION) {
$uuid = $this->transformUnknownUuidIntoUuidVersionZero($uuid);
try {
$uuid = $this->transformUnknownUuidIntoUuidVersionZero($uuid);
} catch (UuidExceptionInterface) {
return false;
}
}

$decoded = $this->decode($uuid);
Expand All @@ -77,6 +84,9 @@ public function isValid(string $prefix, UuidInterface $uuid): bool
return $uuid->equals($encoded);
}

/**
* @throws UuidExceptionInterface
*/
private function transformUnknownUuidIntoUuidVersionZero(UuidInterface $uuid): UuidInterface
{
return UuidV0::fromString($uuid->toString());
Expand Down
13 changes: 13 additions & 0 deletions tests/UuidifierTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
use Ramsey\Uuid\UuidInterface;
use Teamleader\Uuidifier\Nonstandard\UuidV0;
Expand Down Expand Up @@ -73,6 +74,18 @@ public function uuidWithDifferentPrefixIsInvalid()
$this->assertFalse($generator->isValid('bar', $uuid));
}

/**
* @test
*/
public function uuidWithInvalidVersionIsInvalid(): void
{
$generator = new Uuidifier();

$uuid = Uuid::fromString('018dc552-ce8c-77ad-8c27-289ac479d815'); // V7 UUID

Assert::assertFalse($generator->isValid('foo', $uuid));
}

/**
* @test
*/
Expand Down

0 comments on commit 924d842

Please sign in to comment.