| Total Complexity | 49 |
| Total Lines | 147 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like ComparisonUtils often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ComparisonUtils, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 7 | class ComparisonUtils |
||
| 8 | { |
||
| 9 | public static function equals($a, $b): bool |
||
| 35 | } |
||
| 36 | } |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Compares two values according to their type. |
||
| 40 | * |
||
| 41 | * @param mixed $a |
||
| 42 | * @param mixed $b |
||
| 43 | * @return int the comparison result: negative integer, zero, or positive integer if <tt>$this</tt> is less than, |
||
| 44 | * equal to, or greater than <tt>$other</tt>, respectively |
||
| 45 | * @throws IncomparableException if the values are incomparable |
||
| 46 | * @throws \InvalidArgumentException if either of values is <tt>null</tt> |
||
| 47 | */ |
||
| 48 | public static function compareValues($a, $b): int |
||
| 49 | { |
||
| 50 | if ($a === null || $b === null) { |
||
| 51 | throw new \InvalidArgumentException('comparing with null'); |
||
| 52 | } |
||
| 53 | |||
| 54 | if (is_int($a) || is_bool($a)) { |
||
| 55 | return ($a <=> $b); |
||
| 56 | } elseif (is_float($a)) { |
||
| 57 | return self::compareFloats($a, $b); |
||
| 58 | } elseif (is_string($a)) { |
||
| 59 | return strcmp($a, $b); |
||
| 60 | } elseif ($a instanceof IComparable) { |
||
| 61 | return $a->compareTo($b); |
||
| 62 | } elseif (is_array($a) && is_array($b)) { |
||
| 63 | return self::compareArrays($a, $b); |
||
| 64 | } else { |
||
| 65 | throw new IncomparableException(); |
||
| 66 | } |
||
| 67 | } |
||
| 68 | |||
| 69 | public static function compareBigIntegers($a, $b): int |
||
| 70 | { |
||
| 71 | if ($a > PHP_INT_MAX || $b > PHP_INT_MAX || $a < PHP_INT_MIN || $b < PHP_INT_MIN) { |
||
| 72 | return bccomp($a, $b, 0); |
||
| 73 | } else { |
||
| 74 | return (int)$a - (int)$b; |
||
| 75 | } |
||
| 76 | } |
||
| 77 | |||
| 78 | public static function compareFloats($a, $b): int |
||
| 87 | } |
||
| 88 | |||
| 89 | public static function compareArrays(array $a, array $b): int |
||
| 156 |