Last active
August 22, 2022 16:27
-
-
Save BrekiTomasson/17cbd7bf5ec5bcaeb7bf2e30c9439ab8 to your computer and use it in GitHub Desktop.
A simple PHP trait that allows you to compare instances of one class to instances of any other class by implementing the getComparisonValue() method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait IsComparable | |
{ | |
abstract public function getComparisonValue() : int|float|string; | |
/** | |
* @return int<-1, 1> | |
*/ | |
public function compareTo($other) : int | |
{ | |
if (! in_array(self::class, class_uses($other), true)) { | |
throw new RuntimeException('Compared class does not use IsComparable trait!'); | |
} | |
return $this->getComparisonValue() <=> $other->getComparisonValue(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment