$when = new DateTimeImmutable();
$next = $when->modify($difference);
Where $difference is a string such as “+ 10 seconds”. It’s hard to write validation for $difference so it makes sense to just try the modify() and test the result.
In naked PHP I would test for false return value from modify(). But in a Yii environment, I also need to be prepared for yii\base\ErrorException. So I could do something like
try {
$next = $when->modify($difference);
} catch (\yii\base\ErrorException $ignore) {
$next = false;
}
if ($next === false) {
// do the fallback behavior
}
Is this a reasonable approach, assuming I want the code to work with or without Yii’s error handler being involved?
If you don’t need to notify the user about the error and just want to give a fallback value, then you don’t have to worry about the exception handling:.
$when = new DateTimeImmutable();
$next = $when->modify($difference);
if ($next === false) {
$next = $when;
}
If you need to notify the user, then you could write like this:
$when = new DateTimeImmutable();
$next = $when->modify($difference);
if ($next === false) {
throw new yii\base\UserException("Invalid difference specified.");
}
There will be no dedicated try-catch block for this, since the exception will be handled by Yii and the user will be informed of the parameter error by an error view.
I don’t want to notify the error. I just want to use modify() to test the input and handle invalid input, like your validator example. (My input is a batch file so I don’t use a validator but the technique of testing the return value is the same.)
There’s a difficulty that I didn’t elaborate before: PHP issues a warning when modify() is called with invalid argument (in addition to modify() returning false) and Yii’s error handler escalates the warning into a yii\base\ErrorException.
So I wrote the complicated code around modify() that I showed to cope with Yii’s exception and the return value. But I don’t like it and wanted to check with other Yii users about alternatives.