UuidV4.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. * A v4 UUID contains a 122-bit random number.
  13. *
  14. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  15. */
  16. class UuidV4 extends Uuid
  17. {
  18. protected const TYPE = 4;
  19. public function __construct(?string $uuid = null)
  20. {
  21. if (null === $uuid) {
  22. // Generate 36 random hex characters (144 bits)
  23. // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  24. $uuid = bin2hex(random_bytes(18));
  25. // Insert dashes to match the UUID format
  26. // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  27. $uuid[8] = $uuid[13] = $uuid[18] = $uuid[23] = '-';
  28. // Set the UUID version to 4
  29. // xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx
  30. $uuid[14] = '4';
  31. // Set the UUID variant: the 19th char must be in [8, 9, a, b]
  32. // xxxxxxxx-xxxx-4xxx-?xxx-xxxxxxxxxxxx
  33. $uuid[19] = ['8', '9', 'a', 'b', '8', '9', 'a', 'b', 'c' => '8', 'd' => '9', 'e' => 'a', 'f' => 'b'][$uuid[19]] ?? $uuid[19];
  34. $this->uid = $uuid;
  35. } else {
  36. parent::__construct($uuid, true);
  37. }
  38. }
  39. }