Uuid.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /*
  3. * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
  4. * SPDX-License-Identifier: MIT
  5. */
  6. declare(strict_types=1);
  7. namespace Respect\Validation\Rules;
  8. use Respect\Validation\Exceptions\ComponentException;
  9. use function is_string;
  10. use function preg_match;
  11. use function sprintf;
  12. /**
  13. * Validates whether the input is a valid UUID.
  14. *
  15. * It also supports validation of specific versions 1, 3, 4 and 5.
  16. *
  17. * @author Dick van der Heiden <d.vanderheiden@inthere.nl>
  18. * @author Henrique Moody <henriquemoody@gmail.com>
  19. * @author Michael Weimann <mail@michael-weimann.eu>
  20. */
  21. final class Uuid extends AbstractRule
  22. {
  23. /**
  24. * Placeholder in "sprintf()" format used to create the REGEX that validates inputs.
  25. */
  26. private const PATTERN_FORMAT = '/^[0-9a-f]{8}-[0-9a-f]{4}-%s[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i';
  27. /**
  28. * The UUID version to validate for.
  29. *
  30. * @var int|null
  31. */
  32. private $version;
  33. /**
  34. * Initializes the rule with the desired version.
  35. *
  36. * @throws ComponentException when the version is not valid
  37. */
  38. public function __construct(?int $version = null)
  39. {
  40. if ($version !== null && !$this->isSupportedVersion($version)) {
  41. throw new ComponentException(sprintf('Only versions 1, 3, 4, and 5 are supported: %d given', $version));
  42. }
  43. $this->version = $version;
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function validate($input): bool
  49. {
  50. if (!is_string($input)) {
  51. return false;
  52. }
  53. return preg_match($this->getPattern(), $input) > 0;
  54. }
  55. private function isSupportedVersion(int $version): bool
  56. {
  57. return $version >= 1 && $version <= 5 && $version !== 2;
  58. }
  59. private function getPattern(): string
  60. {
  61. if ($this->version !== null) {
  62. return sprintf(self::PATTERN_FORMAT, $this->version);
  63. }
  64. return sprintf(self::PATTERN_FORMAT, '[13-5]');
  65. }
  66. }