From 5618f246c6312ab8160e6ec107be78d17733cd1d Mon Sep 17 00:00:00 2001 From: Avtandil Kikabidze Date: Tue, 6 Feb 2024 13:52:08 +0400 Subject: [PATCH] Improve UUID handling --- src/Lodash/Eloquent/Casts/BinaryUuid.php | 32 +++++++++++++ src/Lodash/Eloquent/UsesUuidAsPrimary.php | 10 +--- src/Lodash/Eloquent/UuidAsPrimary.php | 58 ----------------------- src/Lodash/Support/Uuid.php | 38 +++++++++++++++ 4 files changed, 72 insertions(+), 66 deletions(-) create mode 100644 src/Lodash/Eloquent/Casts/BinaryUuid.php delete mode 100644 src/Lodash/Eloquent/UuidAsPrimary.php create mode 100755 src/Lodash/Support/Uuid.php diff --git a/src/Lodash/Eloquent/Casts/BinaryUuid.php b/src/Lodash/Eloquent/Casts/BinaryUuid.php new file mode 100644 index 0000000..46b2d52 --- /dev/null +++ b/src/Lodash/Eloquent/Casts/BinaryUuid.php @@ -0,0 +1,32 @@ + Uuid::toBinary($value), + ]; + } +} diff --git a/src/Lodash/Eloquent/UsesUuidAsPrimary.php b/src/Lodash/Eloquent/UsesUuidAsPrimary.php index 278593b..7092f07 100644 --- a/src/Lodash/Eloquent/UsesUuidAsPrimary.php +++ b/src/Lodash/Eloquent/UsesUuidAsPrimary.php @@ -4,7 +4,7 @@ namespace Longman\LaravelLodash\Eloquent; -use Ramsey\Uuid\Exception\InvalidArgumentException; +use Longman\LaravelLodash\Support\Uuid as UuidHelper; use Ramsey\Uuid\Uuid; /** @@ -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 diff --git a/src/Lodash/Eloquent/UuidAsPrimary.php b/src/Lodash/Eloquent/UuidAsPrimary.php deleted file mode 100644 index 7b22fda..0000000 --- a/src/Lodash/Eloquent/UuidAsPrimary.php +++ /dev/null @@ -1,58 +0,0 @@ -toString(); - break; - - case 3: - $uuid = Uuid::uuid3()->toString(); - break; - - default: - $uuid = Uuid::uuid4()->toString(); - break; - } - - return $uuid; - } - - public function getIncrementing(): bool - { - return false; - } - - public function getKeyType(): string - { - return 'string'; - } - - protected static function bootUuidAsPrimary(): void - { - /** @var \Illuminate\Database\Eloquent\Model $model */ - static::creating(static function ($model) { - $keyName = $model->getKeyName(); - - if (! empty($model->{$keyName})) { - return; - } - - $uuidVersion = ! empty($model->uuidVersion) ? $model->uuidVersion : Uuid::UUID_TYPE_RANDOM; - - $model->attributes[$keyName] = self::generateUuid($uuidVersion); - }); - } -} diff --git a/src/Lodash/Support/Uuid.php b/src/Lodash/Support/Uuid.php new file mode 100755 index 0000000..a8ec4c7 --- /dev/null +++ b/src/Lodash/Support/Uuid.php @@ -0,0 +1,38 @@ +toString(); + } + + public static function toBinary(string $uuid): string + { + $uuid = UuidFactory::fromString(strtolower($uuid)); + + return $uuid->getBytes(); + } +}