CanCompareValues.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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\Helpers;
  8. use Countable;
  9. use DateTimeImmutable;
  10. use DateTimeInterface;
  11. use Throwable;
  12. use function is_numeric;
  13. use function is_scalar;
  14. use function is_string;
  15. use function mb_strlen;
  16. /**
  17. * Helps to deal with comparable values.
  18. *
  19. * @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
  20. * @author Henrique Moody <henriquemoody@gmail.com>
  21. */
  22. trait CanCompareValues
  23. {
  24. /**
  25. * Tries to convert a value into something that can be compared with PHP operators.
  26. *
  27. * @param mixed $value
  28. *
  29. * @return mixed
  30. */
  31. private function toComparable($value)
  32. {
  33. if ($value instanceof Countable) {
  34. return $value->count();
  35. }
  36. if ($value instanceof DateTimeInterface || !is_string($value) || is_numeric($value) || empty($value)) {
  37. return $value;
  38. }
  39. if (mb_strlen($value) === 1) {
  40. return $value;
  41. }
  42. try {
  43. return new DateTimeImmutable($value);
  44. } catch (Throwable $e) {
  45. return $value;
  46. }
  47. }
  48. /**
  49. * Returns whether the values can be compared or not.
  50. *
  51. * @param mixed $left
  52. * @param mixed $right
  53. */
  54. private function isAbleToCompareValues($left, $right): bool
  55. {
  56. return is_scalar($left) === is_scalar($right);
  57. }
  58. }