-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathStrictPhpComparator.php
More file actions
86 lines (77 loc) · 2.4 KB
/
StrictPhpComparator.php
File metadata and controls
86 lines (77 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Icecave\Parity\Comparator;
/**
* A comparator that approximates a type-strict version of the built-in PHP
* comparison operations.
*/
class StrictPhpComparator implements Comparator
{
/**
* If $relaxNumericComparisons is true, integers and doubles are compared as
* though they were the same type. This allows for natural ordering of
* numbers, ie int(3) < double(4.5) < int(5).
*
* @param bool $relaxNumericComparisons True to relax numeric comparisons; false to compare strictly.
*/
public function __construct($relaxNumericComparisons = true)
{
$this->relaxNumericComparisons = $relaxNumericComparisons;
}
/**
* Compare two values, yielding a result according to the following table:
*
* +--------------------+---------------+
* | Condition | Result |
* +--------------------+---------------+
* | $this == $value | $result === 0 |
* | $this < $value | $result < 0 |
* | $this > $value | $result > 0 |
* +--------------------+---------------+
*
* @param mixed $lhs The first value to compare.
* @param mixed $rhs The second value to compare.
*
* @return int The result of the comparison.
*/
public function compare($lhs, $rhs): int
{
$lhsType = $this->transformTypeName($lhs);
$rhsType = $this->transformTypeName($rhs);
$cmp = strcmp($lhsType, $rhsType);
if ($cmp !== 0) {
return $cmp;
} elseif ($lhs < $rhs) {
return -1;
} elseif ($rhs < $lhs) {
return +1;
}
return 0;
}
/**
* An alias for compare().
*
* @param mixed $lhs The first value to compare.
* @param mixed $rhs The second value to compare.
*
* @return int The result of the comparison.
*/
public function __invoke($lhs, $rhs): int
{
return $this->compare($lhs, $rhs);
}
/**
* @param mixed $value
*
* @return string The effective type name to use when comparing types.
*/
private function transformTypeName($value): string
{
if (is_object($value)) {
return 'object:' . get_class($value);
} elseif (is_integer($value) && $this->relaxNumericComparisons) {
return 'double';
}
return gettype($value);
}
private $relaxNumericComparisons;
}