ailixter / gears-value
调整价值的工程项目
0.1.2
2024-03-15 17:26 UTC
Requires
- php: >=7.1
This package is auto-updated.
Last update: 2024-09-15 18:56:15 UTC
README
调整价值的工程项目。
- 价值类实现了 [value, error] 模式。
- 它提出了简单明了的 ValueInterface。
- 它提供了受保护的验证方法以供覆盖。
- 以及简单的规则
- 值只能被构造,不能被设置
- 无效的值不能被构造
- 带错误信息的值不能被返回
- 如果你愿意,你仍然可以同时获得这两者
基本用法
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()); }