lab/cacme/vendor/workerman/validation/library/Helpers/CanCompareValues.php

69 lines
1.4 KiB
PHP
Raw Permalink Normal View History

2024-08-05 22:57:28 +08:00
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Helpers;
use Countable;
use DateTimeImmutable;
use DateTimeInterface;
use Throwable;
use function is_numeric;
use function is_scalar;
use function is_string;
use function mb_strlen;
/**
* Helps to deal with comparable values.
*
* @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
*/
trait CanCompareValues
{
/**
* 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 Countable) {
return $value->count();
}
if ($value instanceof DateTimeInterface || !is_string($value) || is_numeric($value) || empty($value)) {
return $value;
}
if (mb_strlen($value) === 1) {
return $value;
}
try {
return new DateTimeImmutable($value);
} catch (Throwable $e) {
return $value;
}
}
/**
* Returns whether the values can be compared or not.
*
* @param mixed $left
* @param mixed $right
*/
private function isAbleToCompareValues($left, $right): bool
{
return is_scalar($left) === is_scalar($right);
}
}