Overview

Namespaces

  • PhpCommon
    • Comparison
      • Equivalence
      • Hasher

Interfaces

  • Comparable
  • Comparator
  • Equatable
  • Equivalence
  • Hashable
  • Hasher

Exceptions

  • IncomparableException
  • UnexpectedTypeException
  • Overview
  • Namespace
  • Class

Interface Comparator

A strategy for sorting values.

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method of a collection to allow precise control over its sort order. It can also be used to control the order of certain data structures, such as sorted sets or sorted maps.

The ordering imposed by a Ordering $c on a set of elements S is said to be consistent with an PhpCommon\Comparison\Equivalence $e if and only if $c->compare($a, $b) === 0 has the same boolean value as $e->equivalent($a, $b) for every $a and $b in S.

It is strongly recommended, though not required, that natural orderings be consistent with Equatable::equals(). This is so because in certain cases these methods can be used together in a complementary way to achieve specific results. For example, some structures, such as sets and maps, may use both Equatable::equals() and Ordering::compare() methods as part of the strategy to determine where to store or retrieve data. In the way, such inconsistency may lead to unwanted results.

It is inspired by the Comparator interface, from Java API.

Namespace: PhpCommon\Comparison
Author: Marcos Passos marcos@croct.com
Link: Java Comparator interface
Located at Comparator.php
Methods summary
public integer
# compare( mixed $left, mixed $right )

Compares two values for order.

Compares two values for order.

This method has the following properties:

  • It is reflexive: for any $x, compare($x, $x) === 0.
  • It is antisymmetric: for any $x and $y, if compare($x, $y) <= 0 and compare($y, $x) <= 0, then compare($x, $y) === 0.
  • It is transitive: for any values $x, $y, and $z, if compare($x, $y) <= 0 and compare($y, $z) <= 0, then compare($x, $z) <= 0.

It is strongly recommended, but not strictly required, that (compare($x, $y) === 0) === ($x->equals($y)). Generally speaking, any ordering that violates this condition should clearly indicate this fact. The recommended language is "Note: this class imposes an ordering that is inconsistent with the natural equivalence relation of the values.".

Parameters

$left
The left-hand side to compare with.
$right
The right-hand side to compare with.

Returns

integer

Returns a negative integer, zero, or a positive integer as the left-hand side is less than, equal to or greater than the right-hand side.

Throws

PhpCommon\Comparison\UnexpectedTypeException

If the type of the left-hand side does not match the expected type.


PhpCommon\Comparison\IncomparableException

If the specified values are not comparable under the current order relation.

PHPCommon Comparison API API documentation generated by ApiGen