<?php
use Webmozart\Assert\Assert;
class Foo
{
public function intOnly(int $value) : int
{
Assert::greaterThan($value, 0, '%s is not greater than 0');
Assert::lessThan($value, 10, '%s is not lower than 10');
return $value;
}
public function exactlyTheAnswer($value) : int
{
Assert::eq($value, 42, '%s is not the right answer.');
return $value;
}
public function sum($collection) : int
{
Assert::isTraversable($collection, '%s is not an array or traversable');
$result = 0;
foreach ($collection as $value) {
Assert::integerish($value, '%s? We want integer!');
$result += $value;
}
return $result;
}
}
$foo = new Foo();
try {
$foo->intOnly(10);
} catch (Exception $e) {
dump($e->getMessage());
}
try {
$foo->exactlyTheAnswer(7);
} catch (Exception $e) {
dump($e->getMessage());
}
try {
$foo->sum([1, 1, 'a']);
} catch (Exception $e) {
dump($e->getMessage());
}
try {
$foo->sum(4);
} catch (Exception $e) {
dump($e->getMessage());
}
^ "10 is not lower than 10"
^ "7 is not the right answer."
^ "string? We want integer!"
^ "integer is not an array or traversable"