Created
April 29, 2021 12:33
-
-
Save maryo/e42effdb39379becb4b87256a9b01e54 to your computer and use it in GitHub Desktop.
Simple UUID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types = 1); | |
class Uuid implements Guid | |
{ | |
private string $uuid; | |
public function __construct($uuid = null) | |
{ | |
if ($uuid !== null) { | |
if (!static::isValid($uuid)) { | |
throw new \InvalidArgumentException(sprintf('Invalid UUID "%s".', $uuid)); | |
} | |
$this->uuid = $uuid; | |
return; | |
} | |
$uuid = random_bytes(16); | |
$uuid[6] = $uuid[6] & "\x0F" | "\x4F"; | |
$uuid[8] = $uuid[8] & "\x3F" | "\x80"; | |
$uuid = bin2hex($uuid); | |
$this->uuid = sprintf( | |
'%s-%s-%s-%s-%s', | |
substr($uuid, 0, 8), | |
substr($uuid, 8, 4), | |
substr($uuid, 12, 4), | |
substr($uuid, 16, 4), | |
substr($uuid, 20, 12) | |
); | |
} | |
public static function v4(): self | |
{ | |
return new self(); | |
} | |
public function equalsTo(mixed $value): bool | |
{ | |
return $this == $value; | |
} | |
public function __toString(): string | |
{ | |
return $this->uuid; | |
} | |
public static function isValid(string $uuid): bool | |
{ | |
return function_exists('uuid_is_valid') | |
? uuid_is_valid($uuid) | |
: (bool) preg_match('~^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$~i', $uuid); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment