/src/lib/Helper/Uuid/UuidHelper.php

https://github.com/marius-wieschollek/passwords · PHP · 74 lines · 36 code · 10 blank · 28 comment · 0 complexity · 9518597fddb2b00301c88ffab38ee2b4 MD5 · raw file

  1. <?php
  2. /**
  3. * This file is part of the Passwords App
  4. * created by Marius David Wieschollek
  5. * and licensed under the AGPL.
  6. */
  7. namespace OCA\Passwords\Helper\Uuid;
  8. use Exception;
  9. use OCA\Passwords\Services\LoggingService;
  10. /**
  11. * Class UuidHelper
  12. *
  13. * @package OCA\Passwords\Helper\Uuid
  14. */
  15. class UuidHelper {
  16. /**
  17. * @var LoggingService
  18. */
  19. protected LoggingService $logger;
  20. /**
  21. * UuidHelper constructor.
  22. *
  23. * @param LoggingService $logger
  24. */
  25. public function __construct(LoggingService $logger) {
  26. $this->logger = $logger;
  27. }
  28. /**
  29. * @return string
  30. */
  31. public function generateUuid(): string {
  32. try {
  33. return $this->generateUuidV4();
  34. } catch(Exception $e) {
  35. $this->logger->error('Could not generate UUIDv4');
  36. $this->logger->logException($e);
  37. return $this->generateFallbackUuid();
  38. }
  39. }
  40. /**
  41. * @return string
  42. * @throws Exception
  43. */
  44. protected function generateUuidV4(): string {
  45. return implode('-', [
  46. bin2hex(random_bytes(4)),
  47. bin2hex(random_bytes(2)),
  48. bin2hex(chr((ord(random_bytes(1)) & 0x0F) | 0x40)).bin2hex(random_bytes(1)),
  49. bin2hex(chr((ord(random_bytes(1)) & 0x3F) | 0x80)).bin2hex(random_bytes(1)),
  50. bin2hex(random_bytes(6))
  51. ]);
  52. }
  53. /**
  54. * @return string
  55. */
  56. protected function generateFallbackUuid(): string {
  57. $string = uniqid().uniqid().uniqid();
  58. return substr($string, 0, 8).'-'.
  59. substr($string, 8, 4).'-'.
  60. substr($string, 12, 4).'-'.
  61. substr($string, 16, 4).'-'.
  62. substr($string, 20, 12);
  63. }
  64. }