UUIDUtil.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\DAV;
  4. /**
  5. * UUID Utility.
  6. *
  7. * This class has static methods to generate and validate UUID's.
  8. * UUIDs are used a decent amount within various *DAV standards, so it made
  9. * sense to include it.
  10. *
  11. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  12. * @author Evert Pot (http://evertpot.com/)
  13. * @license http://sabre.io/license/ Modified BSD License
  14. */
  15. class UUIDUtil
  16. {
  17. /**
  18. * Returns a pseudo-random v4 UUID.
  19. *
  20. * This function is based on a comment by Andrew Moore on php.net
  21. *
  22. * @see http://www.php.net/manual/en/function.uniqid.php#94959
  23. *
  24. * @return string
  25. */
  26. public static function getUUID()
  27. {
  28. return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  29. // 32 bits for "time_low"
  30. mt_rand(0, 0xffff), mt_rand(0, 0xffff),
  31. // 16 bits for "time_mid"
  32. mt_rand(0, 0xffff),
  33. // 16 bits for "time_hi_and_version",
  34. // four most significant bits holds version number 4
  35. mt_rand(0, 0x0fff) | 0x4000,
  36. // 16 bits, 8 bits for "clk_seq_hi_res",
  37. // 8 bits for "clk_seq_low",
  38. // two most significant bits holds zero and one for variant DCE1.1
  39. mt_rand(0, 0x3fff) | 0x8000,
  40. // 48 bits for "node"
  41. mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
  42. );
  43. }
  44. /**
  45. * Checks if a string is a valid UUID.
  46. *
  47. * @param string $uuid
  48. *
  49. * @return bool
  50. */
  51. public static function validateUUID($uuid)
  52. {
  53. return 0 !== preg_match(
  54. '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i',
  55. $uuid
  56. );
  57. }
  58. }