Factor.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 abs;
  9. use function is_integer;
  10. use function is_numeric;
  11. /**
  12. * Validates if the input is a factor of the defined dividend.
  13. *
  14. * @author Danilo Correa <danilosilva87@gmail.com>
  15. * @author David Meister <thedavidmeister@gmail.com>
  16. * @author Henrique Moody <henriquemoody@gmail.com>
  17. */
  18. final class Factor extends AbstractRule
  19. {
  20. /**
  21. * @var int
  22. */
  23. private $dividend;
  24. /**
  25. * Initializes the rule.
  26. */
  27. public function __construct(int $dividend)
  28. {
  29. $this->dividend = $dividend;
  30. }
  31. /**
  32. * {@inheritDoc}
  33. */
  34. public function validate($input): bool
  35. {
  36. // Every integer is a factor of zero, and zero is the only integer that
  37. // has zero for a factor.
  38. if ($this->dividend === 0) {
  39. return true;
  40. }
  41. // Factors must be integers that are not zero.
  42. if (!is_numeric($input) || (int) $input != $input || $input == 0) {
  43. return false;
  44. }
  45. $input = (int) abs((int) $input);
  46. $dividend = (int) abs($this->dividend);
  47. // The dividend divided by the input must be an integer if input is a
  48. // factor of the dividend.
  49. return is_integer($dividend / $input);
  50. }
  51. }