Fix casting error in AbstractInterval classes

The classes that are children of "AbstractInterval" convert their values
before comparing them.

Because PHP tries to convert values when making comparisons and an
"DateTime" object cannot be converted to integer or float some
validations would result into PHP triggering an error like:

> Object of class DateTime could not be converted to int
> Object of class DateTime could not be converted to float

This commit prevents that to happen by verifying if both compared values
are scalar or not before comparing them with each other.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
This commit is contained in:
Henrique Moody 2018-07-28 04:45:53 +02:00
parent 4f3aa90d1f
commit 47f21596a5
No known key found for this signature in database
GPG key ID: 221E9281655813A6
5 changed files with 29 additions and 6 deletions

View file

@ -25,6 +25,11 @@ abstract class AbstractInterval extends AbstractRule
$this->inclusive = $inclusive;
}
protected function isAbleToCompareValues($left, $right)
{
return is_scalar($left) === is_scalar($right);
}
protected function filterInterval($value)
{
if (!is_string($value) || is_numeric($value) || empty($value)) {

View file

@ -15,10 +15,17 @@ class Max extends AbstractInterval
{
public function validate($input)
{
if ($this->inclusive) {
return $this->filterInterval($input) <= $this->filterInterval($this->interval);
$filteredInput = $this->filterInterval($input);
$filteredInterval = $this->filterInterval($this->interval);
if (!$this->isAbleToCompareValues($filteredInput, $filteredInterval)) {
return false;
}
return $this->filterInterval($input) < $this->filterInterval($this->interval);
if ($this->inclusive) {
return $filteredInput <= $filteredInterval;
}
return $filteredInput < $filteredInterval;
}
}

View file

@ -15,10 +15,17 @@ class Min extends AbstractInterval
{
public function validate($input)
{
if ($this->inclusive) {
return $this->filterInterval($input) >= $this->filterInterval($this->interval);
$filteredInput = $this->filterInterval($input);
$filteredInterval = $this->filterInterval($this->interval);
if (!$this->isAbleToCompareValues($filteredInput, $filteredInterval)) {
return false;
}
return $this->filterInterval($input) > $this->filterInterval($this->interval);
if ($this->inclusive) {
return $filteredInput >= $filteredInterval;
}
return $filteredInput > $filteredInterval;
}
}

View file

@ -62,6 +62,8 @@ class MaxTest extends \PHPUnit_Framework_TestCase
[200, false, 250],
[200, false, 1500],
[200, false, 200],
[1900, false, '2018-01-25'],
[10.5, false, '2018-01-25'],
];
}
}

View file

@ -70,6 +70,8 @@ class MinTest extends \PHPUnit_Framework_TestCase
[0, false, -250],
[0, false, -50],
[50, false, 50],
[2040, false, '2018-01-25'],
[10.5, false, '2018-01-25'],
];
}
}