Last active
July 3, 2017 13:55
-
-
Save finagin/11f70045c85e07ac4d939e0e9525af70 to your computer and use it in GitHub Desktop.
Comparable & Equalsable abstract class
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
<?php | |
namespace Finagin\Ad\Helpers; | |
use Exception; | |
abstract class AbstractComparable | |
{ | |
/** | |
* Equals $this and $other instances | |
* | |
* @param $other | |
* @param bool $strict | |
* | |
* @return bool | |
*/ | |
public function equals($other, $strict = true) | |
{ | |
return $this->compareTo($other, $strict) === 0; | |
} | |
/** | |
* Compare $this and $other instances | |
* | |
* @param $other | |
* @param bool $strict | |
* | |
* @return mixed | |
* @throws Exception | |
*/ | |
public function compareTo($other, $strict = true) | |
{ | |
$staticClass = static::class; | |
if ($strict && ! ($other instanceof $staticClass)) { | |
throw new Exception('"'.get_class($other).'"" doesn\'t instanceof "'.static::class.'"'); | |
} | |
return $this->__compare($other); | |
} | |
/** | |
* Compare $this and $other instances | |
* | |
* @param $other | |
* | |
* @return mixed | |
*/ | |
abstract protected function __compare($other); | |
} |
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
<?php | |
namespace Finagin; | |
$x = new TestClass(1); | |
$a = new TestClass(0); | |
$b = new TestClass(1); | |
$c = new TestClass(2); | |
$e = new OtherClass(1); | |
$x->compareTo($a); // 1 | |
$x->compareTo($b); // 0 | |
$x->compareTo($c); // -1 | |
$x->compareTo($d); // throw Exception | |
$x->equals($a); // false | |
$x->equals($b); // true | |
$x->equals($c); // false | |
$x->equals($d); // throw Exception |
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
<?php | |
namespace Finagin; | |
use Finagin\Helpers\AbstractComparable; | |
class TestClass extends AbstractComparable | |
{ | |
protected $value; | |
public function __construct($value) | |
{ | |
$this->value = $value; | |
} | |
public function getValue() | |
{ | |
return $this->value; | |
} | |
protected function __compare($other) | |
{ | |
if ($this->value > $other->getValue()) { | |
return 1; | |
} elseif ($this->value < $other->getValue()) { | |
return -1; | |
} else { | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment