Skip to content

Commit

Permalink
Improve UUID handling
Browse files Browse the repository at this point in the history
  • Loading branch information
akalongman committed Feb 6, 2024
1 parent a91979b commit 5618f24
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 66 deletions.
32 changes: 32 additions & 0 deletions src/Lodash/Eloquent/Casts/BinaryUuid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Longman\LaravelLodash\Eloquent\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Longman\LaravelLodash\Support\Uuid;

class BinaryUuid implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): ?string
{
if (blank($value)) {
return null;
}

return Uuid::toString($value);
}

public function set(Model $model, string $key, mixed $value, array $attributes): ?array
{
if (blank($value)) {
return null;
}

return [
$key => Uuid::toBinary($value),
];
}
}
10 changes: 2 additions & 8 deletions src/Lodash/Eloquent/UsesUuidAsPrimary.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace Longman\LaravelLodash\Eloquent;

use Ramsey\Uuid\Exception\InvalidArgumentException;
use Longman\LaravelLodash\Support\Uuid as UuidHelper;
use Ramsey\Uuid\Uuid;

/**
Expand All @@ -14,13 +14,7 @@ trait UsesUuidAsPrimary
{
public function isUuidBinary(string $value): bool
{
try {
Uuid::fromBytes($value);
} catch (InvalidArgumentException) {
return false;
}

return true;
return UuidHelper::isBinary($value);
}

public function getIncrementing(): bool
Expand Down
58 changes: 0 additions & 58 deletions src/Lodash/Eloquent/UuidAsPrimary.php

This file was deleted.

38 changes: 38 additions & 0 deletions src/Lodash/Support/Uuid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Longman\LaravelLodash\Support;

use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Uuid as UuidFactory;

use function strtolower;

class Uuid
{
public static function isBinary(string $value): bool
{
try {
UuidFactory::fromBytes($value);
} catch (InvalidArgumentException) {
return false;
}

return true;
}

public static function toString(string $uuid): string
{
$uuid = UuidFactory::fromBytes($uuid);

return $uuid->toString();
}

public static function toBinary(string $uuid): string
{
$uuid = UuidFactory::fromString(strtolower($uuid));

return $uuid->getBytes();
}
}

0 comments on commit 5618f24

Please sign in to comment.