achse/php-comparable-interface

IComparable interface and ComparisonMethods trait.

1.0.2 2016-07-10 09:47 UTC

README

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();
    }
    
}