Isbn.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 function implode;
  9. use function is_scalar;
  10. use function preg_match;
  11. use function sprintf;
  12. /**
  13. * Validates whether the input is a valid ISBN (International Standard Book Number) or not.
  14. *
  15. * @author Henrique Moody <henriquemoody@gmail.com>
  16. * @author Moritz Fromm <moritzgitfromm@gmail.com>
  17. */
  18. final class Isbn extends AbstractRule
  19. {
  20. /**
  21. * @see https://howtodoinjava.com/regex/java-regex-validate-international-standard-book-number-isbns
  22. */
  23. private const PIECES = [
  24. '^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})',
  25. '[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)',
  26. '(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$',
  27. ];
  28. /**
  29. * {@inheritDoc}
  30. */
  31. public function validate($input): bool
  32. {
  33. if (!is_scalar($input)) {
  34. return false;
  35. }
  36. return preg_match(sprintf('/%s/', implode(self::PIECES)), (string) $input) > 0;
  37. }
  38. }