[13.x] Add a `strict` flag to `InteractsWithData`

Merged
IN
2d ago
+250-9

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:

  1. It can trigger exceptions if unexpected data is provided (particularly arrays)
    Our error logs are littered with random Array to string conversion exceptions that actually don't matter (it's usually someone trying to find bugs as part of our bug bounty program). A request with ?name[]=chris causes $request->string('name') to throw.

  2. You can't use them for "give me a valid value or else the default" reliably
    For example, a request with ?count=abc123 will return 0 for $request->integer('count', 5) — the "abc123" will happily cast to 0 and your default value is never used.

This adds a new optional strict flag to:

MethodStrict 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.