Equivalent.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 is_scalar;
  9. use function mb_strtoupper;
  10. /**
  11. * Validates if the input is equivalent to some value.
  12. *
  13. * @author Henrique Moody <henriquemoody@gmail.com>
  14. */
  15. final class Equivalent extends AbstractRule
  16. {
  17. /**
  18. * @var mixed
  19. */
  20. private $compareTo;
  21. /**
  22. * Initializes the rule.
  23. *
  24. * @param mixed $compareTo
  25. */
  26. public function __construct($compareTo)
  27. {
  28. $this->compareTo = $compareTo;
  29. }
  30. /**
  31. * {@inheritDoc}
  32. */
  33. public function validate($input): bool
  34. {
  35. if (is_scalar($input)) {
  36. return $this->isStringEquivalent((string) $input);
  37. }
  38. return $input == $this->compareTo;
  39. }
  40. private function isStringEquivalent(string $input): bool
  41. {
  42. if (!is_scalar($this->compareTo)) {
  43. return false;
  44. }
  45. return mb_strtoupper((string) $input) === mb_strtoupper((string) $this->compareTo);
  46. }
  47. }