2015-09-06 17:37:08 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
/*
|
2023-02-17 05:13:51 +01:00
|
|
|
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
|
|
|
|
* SPDX-License-Identifier: MIT
|
2015-09-06 17:37:08 +02:00
|
|
|
*/
|
|
|
|
|
2017-11-19 19:01:31 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2015-09-06 17:37:08 +02:00
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2018-09-30 15:43:15 +02:00
|
|
|
use function abs;
|
|
|
|
use function is_integer;
|
|
|
|
use function is_numeric;
|
2015-09-06 17:37:08 +02:00
|
|
|
|
|
|
|
/**
|
2018-09-30 15:43:15 +02:00
|
|
|
* Validates if the input is a factor of the defined dividend.
|
|
|
|
*
|
|
|
|
* @author Danilo Correa <danilosilva87@gmail.com>
|
2015-09-06 17:37:08 +02:00
|
|
|
* @author David Meister <thedavidmeister@gmail.com>
|
2018-09-30 15:43:15 +02:00
|
|
|
* @author Henrique Moody <henriquemoody@gmail.com>
|
2015-09-06 17:37:08 +02:00
|
|
|
*/
|
2018-09-30 15:43:15 +02:00
|
|
|
final class Factor extends AbstractRule
|
2015-09-06 17:37:08 +02:00
|
|
|
{
|
2018-09-30 15:43:15 +02:00
|
|
|
/**
|
|
|
|
* @var int
|
|
|
|
*/
|
|
|
|
private $dividend;
|
2015-09-06 17:37:08 +02:00
|
|
|
|
2018-09-30 15:43:15 +02:00
|
|
|
/**
|
|
|
|
* Initializes the rule.
|
|
|
|
*/
|
|
|
|
public function __construct(int $dividend)
|
2015-09-06 17:37:08 +02:00
|
|
|
{
|
2018-09-30 15:43:15 +02:00
|
|
|
$this->dividend = $dividend;
|
2015-09-06 17:37:08 +02:00
|
|
|
}
|
|
|
|
|
2018-09-30 15:43:15 +02:00
|
|
|
/**
|
2019-04-05 14:33:00 +02:00
|
|
|
* {@inheritDoc}
|
2018-09-30 15:43:15 +02:00
|
|
|
*/
|
2018-01-28 15:41:31 +01:00
|
|
|
public function validate($input): bool
|
2015-09-06 17:37:08 +02:00
|
|
|
{
|
|
|
|
// Every integer is a factor of zero, and zero is the only integer that
|
|
|
|
// has zero for a factor.
|
2019-02-09 13:28:08 +01:00
|
|
|
if ($this->dividend === 0) {
|
2015-09-06 17:37:08 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Factors must be integers that are not zero.
|
2019-02-09 13:28:08 +01:00
|
|
|
if (!is_numeric($input) || (int) $input != $input || $input == 0) {
|
2015-09-06 17:37:08 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2020-07-22 14:02:39 +02:00
|
|
|
$input = (int) abs((int) $input);
|
2015-09-06 17:37:08 +02:00
|
|
|
$dividend = (int) abs($this->dividend);
|
|
|
|
|
|
|
|
// The dividend divided by the input must be an integer if input is a
|
|
|
|
// factor of the dividend.
|
|
|
|
return is_integer($dividend / $input);
|
|
|
|
}
|
|
|
|
}
|