respect-validation/library/Helpers/ComparisonHelper.php
Henrique Moody 60e3fc3740
Refactor "Between" rule
The "Between" rule was extending the "AllOf" rule and adding "Max" and
"Min" rules to the chain. Because of that, when the rule failed we could
get the "MinException" or the "MaxException" exception, and only if both
failed that we would get the "BetweenException".

With this change it will always get the "BetweenException" which makes
it more explicit.

Also, the "Between" is not using the same standard required in the
Contribution Guidelines.
2018-03-03 18:06:26 +01:00

54 lines
1.1 KiB
PHP

<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Helpers;
use DateTimeImmutable;
use DateTimeInterface;
use Exception;
use function is_numeric;
use function is_string;
use function mb_strlen;
/**
* Helps to deal with comparable values.
*
* @author Henrique Moody <henriquemoody@gmail.com>
*/
trait ComparisonHelper
{
/**
* Tries to convert a value into something that can be compared with PHP operators.
*
* @param mixed $value
*
* @return mixed
*/
private function toComparable($value)
{
if ($value instanceof DateTimeInterface || !is_string($value) || is_numeric($value) || empty($value)) {
return $value;
}
if (1 === mb_strlen($value)) {
return $value;
}
try {
return new DateTimeImmutable($value);
} catch (Exception $e) {
return $value;
}
}
}