Skip to content

Instantly share code, notes, and snippets.

@marcosh
Created Jan 16, 2020
Embed
What would you like to do?
Boolean implementation in PHP
<?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