Uuid.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Uid;
  11. /**
  12. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  13. *
  14. * @see https://datatracker.ietf.org/doc/html/rfc9562/#section-6.6 for details about namespaces
  15. */
  16. class Uuid extends AbstractUid
  17. {
  18. public const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  19. public const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
  20. public const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8';
  21. public const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8';
  22. public const FORMAT_BINARY = 1;
  23. public const FORMAT_BASE_32 = 1 << 1;
  24. public const FORMAT_BASE_58 = 1 << 2;
  25. public const FORMAT_RFC_4122 = 1 << 3;
  26. public const FORMAT_RFC_9562 = self::FORMAT_RFC_4122;
  27. public const FORMAT_ALL = -1;
  28. protected const TYPE = 0;
  29. protected const NIL = '00000000-0000-0000-0000-000000000000';
  30. protected const MAX = 'ffffffff-ffff-ffff-ffff-ffffffffffff';
  31. public function __construct(string $uuid, bool $checkVariant = false)
  32. {
  33. $type = preg_match('{^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$}Di', $uuid) ? (int) $uuid[14] : false;
  34. if (false === $type || (static::TYPE ?: $type) !== $type) {
  35. throw new \InvalidArgumentException(\sprintf('Invalid UUID%s: "%s".', static::TYPE ? 'v'.static::TYPE : '', $uuid));
  36. }
  37. $this->uid = strtolower($uuid);
  38. if ($checkVariant && !\in_array($this->uid[19], ['8', '9', 'a', 'b'], true)) {
  39. throw new \InvalidArgumentException(\sprintf('Invalid UUID%s: "%s".', static::TYPE ? 'v'.static::TYPE : '', $uuid));
  40. }
  41. }
  42. public static function fromString(string $uuid): static
  43. {
  44. $uuid = self::transformToRfc9562($uuid, self::FORMAT_ALL);
  45. if (__CLASS__ !== static::class || 36 !== \strlen($uuid)) {
  46. return new static($uuid);
  47. }
  48. if (self::NIL === $uuid) {
  49. return new NilUuid();
  50. }
  51. if (self::MAX === $uuid = strtr($uuid, 'F', 'f')) {
  52. return new MaxUuid();
  53. }
  54. if (!\in_array($uuid[19], ['8', '9', 'a', 'b', 'A', 'B'], true)) {
  55. return new self($uuid);
  56. }
  57. return match ((int) $uuid[14]) {
  58. UuidV1::TYPE => new UuidV1($uuid),
  59. UuidV3::TYPE => new UuidV3($uuid),
  60. UuidV4::TYPE => new UuidV4($uuid),
  61. UuidV5::TYPE => new UuidV5($uuid),
  62. UuidV6::TYPE => new UuidV6($uuid),
  63. UuidV7::TYPE => new UuidV7($uuid),
  64. UuidV8::TYPE => new UuidV8($uuid),
  65. default => new self($uuid),
  66. };
  67. }
  68. final public static function v1(): UuidV1
  69. {
  70. return new UuidV1();
  71. }
  72. final public static function v3(self $namespace, string $name): UuidV3
  73. {
  74. // don't use uuid_generate_md5(), some versions are buggy
  75. $uuid = md5(hex2bin(str_replace('-', '', $namespace->uid)).$name, true);
  76. return new UuidV3(self::format($uuid, '-3'));
  77. }
  78. final public static function v4(): UuidV4
  79. {
  80. return new UuidV4();
  81. }
  82. final public static function v5(self $namespace, string $name): UuidV5
  83. {
  84. // don't use uuid_generate_sha1(), some versions are buggy
  85. $uuid = substr(sha1(hex2bin(str_replace('-', '', $namespace->uid)).$name, true), 0, 16);
  86. return new UuidV5(self::format($uuid, '-5'));
  87. }
  88. final public static function v6(): UuidV6
  89. {
  90. return new UuidV6();
  91. }
  92. final public static function v7(): UuidV7
  93. {
  94. return new UuidV7();
  95. }
  96. final public static function v8(string $uuid): UuidV8
  97. {
  98. return new UuidV8($uuid);
  99. }
  100. /**
  101. * @param int-mask-of<Uuid::FORMAT_*> $format
  102. */
  103. public static function isValid(string $uuid /* , int $format = self::FORMAT_RFC_9562 */): bool
  104. {
  105. $format = 1 < \func_num_args() ? func_get_arg(1) : self::FORMAT_RFC_9562;
  106. if (36 === \strlen($uuid) && !($format & self::FORMAT_RFC_9562)) {
  107. return false;
  108. }
  109. if (false === $uuid = self::transformToRfc9562($uuid, $format)) {
  110. return false;
  111. }
  112. if (self::NIL === $uuid && \in_array(static::class, [__CLASS__, NilUuid::class], true)) {
  113. return true;
  114. }
  115. if (self::MAX === strtr($uuid, 'F', 'f') && \in_array(static::class, [__CLASS__, MaxUuid::class], true)) {
  116. return true;
  117. }
  118. if (!preg_match('{^[0-9a-f]{8}(?:-[0-9a-f]{4}){2}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$}Di', $uuid)) {
  119. return false;
  120. }
  121. return __CLASS__ === static::class || static::TYPE === (int) $uuid[14];
  122. }
  123. public function toBinary(): string
  124. {
  125. return hex2bin(str_replace('-', '', $this->uid));
  126. }
  127. /**
  128. * Returns the identifier as a RFC 9562/4122 case insensitive string.
  129. *
  130. * @see https://datatracker.ietf.org/doc/html/rfc9562/#section-4
  131. *
  132. * @example 09748193-048a-4bfb-b825-8528cf74fdc1 (len=36)
  133. */
  134. public function toRfc4122(): string
  135. {
  136. return $this->uid;
  137. }
  138. public function compare(AbstractUid $other): int
  139. {
  140. if (false !== $cmp = uuid_compare($this->uid, $other->uid)) {
  141. return $cmp;
  142. }
  143. return parent::compare($other);
  144. }
  145. private static function format(string $uuid, string $version): string
  146. {
  147. $uuid[8] = $uuid[8] & "\x3F" | "\x80";
  148. $uuid = substr_replace(bin2hex($uuid), '-', 8, 0);
  149. $uuid = substr_replace($uuid, $version, 13, 1);
  150. $uuid = substr_replace($uuid, '-', 18, 0);
  151. return substr_replace($uuid, '-', 23, 0);
  152. }
  153. /**
  154. * Transforms a binary string, a base-32 string or a base-58 string to a RFC9562 string.
  155. *
  156. * @param int-mask-of<Uuid::FORMAT_*> $format
  157. *
  158. * @return string|false The RFC9562 string or false if the format doesn't match the input
  159. */
  160. private static function transformToRfc9562(string $uuid, int $format): string|false
  161. {
  162. $inputUuid = $uuid;
  163. $fromBase58 = false;
  164. if (22 === \strlen($uuid) && 22 === strspn($uuid, BinaryUtil::BASE58['']) && $format & self::FORMAT_BASE_58) {
  165. $uuid = str_pad(BinaryUtil::fromBase($uuid, BinaryUtil::BASE58), 16, "\0", \STR_PAD_LEFT);
  166. $fromBase58 = true;
  167. }
  168. // base-58 are always transformed to binary string, but they must only be valid when the format is FORMAT_BASE_58
  169. if (16 === \strlen($uuid) && $format & self::FORMAT_BINARY || $fromBase58 && $format & self::FORMAT_BASE_58) {
  170. // don't use uuid_unparse(), it's slower
  171. $uuid = bin2hex($uuid);
  172. $uuid = substr_replace($uuid, '-', 8, 0);
  173. $uuid = substr_replace($uuid, '-', 13, 0);
  174. $uuid = substr_replace($uuid, '-', 18, 0);
  175. $uuid = substr_replace($uuid, '-', 23, 0);
  176. } elseif (26 === \strlen($uuid) && Ulid::isValid($uuid) && $format & self::FORMAT_BASE_32) {
  177. $ulid = new NilUlid();
  178. $ulid->uid = strtoupper($uuid);
  179. $uuid = $ulid->toRfc4122();
  180. }
  181. if ($inputUuid === $uuid && !($format & self::FORMAT_RFC_9562)) {
  182. // input format doesn't match the input string
  183. return false;
  184. }
  185. return $uuid;
  186. }
  187. }