[13.x] Add a `strict` flag to `InteractsWithData`
Right now the helper methods on InteractsWithData like integer() or boolean() just do a plain cast.
There are two scenarios where this isn't ideal:
-
It can trigger exceptions if unexpected data is provided (particularly arrays)
Our error logs are littered with randomArray to string conversionexceptions that actually don't matter (it's usually someone trying to find bugs as part of our bug bounty program). A request with?name[]=chriscauses$request->string('name')to throw. -
You can't use them for "give me a valid value or else the default" reliably
For example, a request with?count=abc123will return0for$request->integer('count', 5)— the"abc123"will happily cast to0and your default value is never used.
This adds a new optional strict flag to:
| Method | Strict mode behavior |
|---|---|
string() | will return $default if the input isn't a string or number |
boolean() | will return $default if the value is missing or not one of 1, true, on, yes, 0, false, off, and no (that's the list that FILTER_VALIDATE_BOOLEAN uses) |
integer() | will return $default if the value is not an integer |
float() | will return $default if the value is not a float |
[!note]
There are a few other methods that this could expand to, most notably array() and collect(), but they come with complications that I'll address later if this gets merged.
In many cases, this can be mitigated with validation, but there are lots of scenarios where the logic is effectively "if they provide an integer here, use it" and adding a validation step can feel quite heavy-handed in those scenarios.