IComparable interface and ComparisonMethods trait.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
tests
.gitignore
.travis.yml
LICENSE
README.md
composer.json

README.md

Downloads this Month Latest Stable Version Build Status Scrutinizer Code Quality Coverage Status

Note: RFC for Comparable interface into PHP is there from Sep 2010: https://wiki.php.net/rfc/comparable

Installation

composer require achse/php-comparable-interface

Usage

Interface package for: IComparable. introducing methods:

  • compare(IComparable $other) : int
  • isEqual(IComparable $other) : bool
  • isLessThan(IComparable $other) : bool
  • isLessThanOrEqual(IComparable $other) : bool
  • isGreaterThan(IComparable $other) : bool
  • isGreaterThanOrEqual(IComparable $other) : bool

Package also provides trait ComparisonMethods that implements all mentioned methods except compare. All you have to do is to implement that method in your class and use trait to have all other methods from interface.

Creation of this interface is mainly motivated by need in packages like:

Example usage (tests/DummyInt.php)

class DummyInt implements IComparable
{

    use ComparisonMethods;

    /**
     * @var int
     */
    private $int;

    /**
     * @param int $int
     */
    public function __construct(int $int)
    {
        $this->int = $int;
    }

    /**
     * @return int
     */
    public function getInt()
    {
        return $this->int;
    }

    /**
     * @inheritdoc
     */
    public function compare(IComparable $other) : int
    {
        if (!$other instanceof static) {
            throw new LogicException('You cannot compare sheep with the goat.');
        }

        return $this->int <=> $other->getInt();
    }
    
}