[11.x] add lazy default to when helper #52747
Merged
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
PR #52665 added a new helper to Laravel:
when()It simplifies the evaluation of a condition to output a value similar to PHP's ternary operator, with the
falsebranch always returningnull.This PR:
false.Illuminate\Support\Traits\Conditionable@when()method, by passing the$conditionvalue to thevalue()helper, so it is passed down as an argument to any\Closureused as thetrueordefaultvalues.Notes
Why not use the null-coalesce (
??) operator?One could argue that the
$defaultparameter is not needed, as a developer could use the null-coalesce operator instead, like this:But that doesn't allow for the lazy evaluation of the
$defaultvalue, in case we want to use a dynamic default value, for example, when usingPennantto test a new design:In the example above, the
$defaultvalue would be lazily evaluated when a guest is visiting the application.Also, as we are passing the
$conditionvalue down to the truthy\Closure, we don't need toAuth::useragain.Breaking change
As a new parameter is added, it could be considered a breaking change.
But the
when()helper was just added in today's release, also the$defaultparameter is optional with anulldefault value, preserving the original behavior.Disclaimer
I suggested this implementation in the original PR in this comment: #52665 (comment)
But, although the author of that PR was very welcoming of all suggestions, the addition of the
$defaultvalue didn't make the cut.Post Script
I changed some of the original test assertions to use
assertNull(...)instead ofassertEquals(null, ...).