Skip to content

Instantly share code, notes, and snippets.

@marcosh
Created January 16, 2020 11:16
Show Gist options
  • Select an option

  • Save marcosh/b43063e31bb5d8dbd6019be36ea4b3c1 to your computer and use it in GitHub Desktop.

Select an option

Save marcosh/b43063e31bb5d8dbd6019be36ea4b3c1 to your computer and use it in GitHub Desktop.

Revisions

  1. marcosh created this gist Jan 16, 2020.
    83 changes: 83 additions & 0 deletions Boolean.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,83 @@
    <?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());
    }
    }