Is there any library for refined types in php that can allow me to do something like this?
function getAge(int positive $age){
...
}
getAge(-1) // error -1 < 0
Thanks!
You would need to implement Refinement-Types at the engine level. No one did this yet.
Or use a userland Preprocessor, like http://github.com/marcioAlmada/yay.
Or implement the refined types as Value Objects, e.g.
class PositiveInteger
{
private $value;
public static function assertValid(int $value) {
if ($value < 0) {
throw new InvalidArgumentException("Not positive");
}
}
public function __construct(int $value)
{
static::assertValid($value);
$this->value = $value;
}
public function getValue(): int
{
return $this->value;
}
public function __toString(): string
{
return (string) $this->value;
}
}
However, this means the int is no longer a scalar and cannot be used in the same way as you'd use a scalar, e.g. all operations would need to be methods. You won't be able to do $age++
anymore.