Skip to content

Instantly share code, notes, and snippets.

@finagin
Last active July 3, 2017 13:55
Show Gist options
  • Save finagin/11f70045c85e07ac4d939e0e9525af70 to your computer and use it in GitHub Desktop.
Save finagin/11f70045c85e07ac4d939e0e9525af70 to your computer and use it in GitHub Desktop.
Comparable & Equalsable abstract class
<?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);
}
<?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
<?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