ailixter/gears-value

The project that gears values

0.1.2 2024-03-15 17:26 UTC

This package is auto-updated.

Last update: 2024-03-15 17:57:45 UTC


README

The project that gears values.

  1. Value class implements [value, error] pattern.
  2. It proposes simple and clear ValueInterface.
  3. It provides protected validation method to override.
  4. And simple rules
    • value may only be constructed, not set
    • invalid value cannot be constructed
    • value with errors cannot be returned
    • you can get both if you're willing to

Basic Usage

    use Ailixter\Gears\IntValue;
    use Ailixter\Gears\ValueInterface;

    class Positive extends IntValue
    {
        protected function validate()
        {
            if ($this->getValue() < 1) {
                $this->addError('value', 'is not positive');
            }
        }
    }

    function calculate(int $int): Positive
    {
        $result = new Positive($int * $int);
        if ($result->getValue() > 81) {
            $result->addError('value', 'too big');
        }
        return $result;
    }

    function readyForUnexpected(IntValue $int)
    {
        if ($int->getErrors()) {
            $result = 81;
        } else {
            $result = $int->getValue();
        }
        echo $result - 1;
    }

    function wantNoUnexpected(int $int)
    {
        echo $int - 1;
    }

    readyForUnexpected(calculate(8));       // 63
    readyForUnexpected(calculate(10));      // 80

    wantNoUnexpected(calculate(8)->get());  // 63

    try {
        wantNoUnexpected(calculate(10)->get()); // exception - too big
    } catch (Ailixter\Gears\Exceptions\ValueException $ve) {
        echo PHP_EOL, $ve->getMessage(), ': ';
        print_r($ve->getValue()->getErrors());
    }
    try {
        calculate(0);                      // exception - not positive
    } catch (Ailixter\Gears\Exceptions\ValueException $ve) {
        echo PHP_EOL, $ve->getMessage(), ': ';
        print_r($ve->getValue()->getErrors());
    }