fleshgrinder / comparable
Interface for custom compare checks of objects.
Installs: 5 052
Dependents: 1
Suggesters: 3
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
This package is not auto-updated.
Last update: 2020-01-16 23:26:01 UTC
README
Comparable
Interface to implement custom comparison logic for classes instead of writing them inline over and over again.
Provided is the interface itself that establishes the contract that implementing classes have to have the compare method. Furthermore a specific exception is provided that can be used to notify callers that a comparison of the passed value is not possible. Last but not least a dummy class that can be used in tests as a substitute for doubles, stubs, or mocks is included as well.
Installation
Open a terminal, enter your project directory and execute the following command to add this package to your dependencies:
$ composer require fleshgrinder/comparable
This command requires you to have Composer installed globally, as explained in the installation chapter of the Composer documentation.
Usage
Simply implement the interface and the required compareTo
method.
class YourClass implements Comparable { const TOLERANCE = 0.0001; protected $value; public function __construct($value) { $this->value = (float) $value; } /** * @inheritDoc */ public function compareTo($other) { if (($other instanceof $this) === false) { throw new UncomparableException(); } $diff = $other->value() - $this->value; if ($diff > static::TOLERANCE) { return 1; } if ($diff < -static::TOLERANCE) { return -1; } return 0; } }