AbstractComparison.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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\Helpers\CanCompareValues;
  9. /**
  10. * Abstract class to help on creating rules that compare value.
  11. *
  12. * @author Henrique Moody <henriquemoody@gmail.com>
  13. */
  14. abstract class AbstractComparison extends AbstractRule
  15. {
  16. use CanCompareValues;
  17. /**
  18. * @var mixed
  19. */
  20. private $compareTo;
  21. /**
  22. * Compare both values and return whether the comparison is valid or not.
  23. *
  24. * @param mixed $left
  25. * @param mixed $right
  26. */
  27. abstract protected function compare($left, $right): bool;
  28. /**
  29. * Initializes the rule by setting the value to be compared to the input.
  30. *
  31. * @param mixed $maxValue
  32. */
  33. public function __construct($maxValue)
  34. {
  35. $this->compareTo = $maxValue;
  36. }
  37. /**
  38. * {@inheritDoc}
  39. */
  40. public function validate($input): bool
  41. {
  42. $left = $this->toComparable($input);
  43. $right = $this->toComparable($this->compareTo);
  44. if (!$this->isAbleToCompareValues($left, $right)) {
  45. return false;
  46. }
  47. return $this->compare($left, $right);
  48. }
  49. }