UUIDUtil.php 1.7 KB

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