Created
January 16, 2020 11:16
-
-
Save marcosh/b43063e31bb5d8dbd6019be36ea4b3c1 to your computer and use it in GitHub Desktop.
Boolean implementation in PHP
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 | |
declare(strict_types=1); | |
namespace Marcosh\PhpValidationDSL; | |
final class Boolean | |
{ | |
/** @var Bool */ | |
private $isTrue; | |
private function __construct(bool $isTrue) | |
{ | |
$this->isTrue = $isTrue; | |
} | |
public static function true(): self | |
{ | |
return new self(true); | |
} | |
public static function false(): self | |
{ | |
return new self(false); | |
} | |
/** | |
* @template T | |
* @param mixed $ifTrue | |
* @param mixed $ifFalse | |
* @psalm-param T $ifTrue | |
* @psalm-param T $ifFalse | |
* @return mixed | |
* @psalm-return T | |
*/ | |
public function evalBool($ifTrue, $ifFalse) | |
{ | |
if ($this->isTrue) { | |
return $ifTrue; | |
} | |
return $ifFalse; | |
} | |
public function fromEnum(): int | |
{ | |
return $this->evalBool(1, 0); | |
} | |
public function show(): string | |
{ | |
return $this->evalBool('true', 'false'); | |
} | |
public function compare(self $that): Ordering | |
{ | |
return $this->evalBool( | |
$that->evalBool(Ordering::EQ(), Ordering::GT()), | |
$that->evalBool(Ordering::LT(), Ordering::EQ()) | |
); | |
} | |
public function and(self $that): self | |
{ | |
return $this->evalBool( | |
$that->evalBool(self::true(), self::false()), | |
$that->evalBool(self::false(), self::false()) | |
); | |
} | |
public function or(self $that): self | |
{ | |
return $this->evalBool( | |
$that->evalBool(self::true(), self::true()), | |
$that->evalBool(self::true(), self::false()) | |
); | |
} | |
public function not(): self | |
{ | |
return $this->evalBool(self::false(), self::true()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment