Add a fluent Stringable Str::of($string)->if()
method to allow longer chaining of a Stringable, based on the Stringable itself
#40038
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.
This Pull Request adds the ability to use an
if()
method on an instance of Stringable. This would allow developers to chain more Stringables and keep the code cleaner.What & why
In certain situations, developers need to modify a fluent Stringable based on the value of the Stringable itself. The
when()
methods do not allow this, because they accept a boolean, which is based on a condition outside of the Stringable, and not a condition on the contents of the Stringable itself. I think that an example will make this more clear.Consider the following scenario, where I want to append a value to a string if the string is numeric. In the current situation, we have to do something like this:
As you see, we need to extract the Stringable to a separate before before we can make assertions on it. This causes our code code to become more unclear. In particular in cases where there is no need to a separate
$stringable
, this is needless.With the new
if()
method, we could refactor the above example to:Or, even shorter with PHP 7.4 short function calls:
If you only want to modify the string in one of the two cases, you can just pass
null
instead of a callback. The third parameter can be omitted entirely.The whole
if()
method returns a new instance ofStringable
, so everything is chainable. That means that you could chain multipleif()
s and easily create complex strings.Example 2
Imagine the following long and boring procedural code:
With the
if()
helper, we can replace it with the following:Both will output:
It would also allow to perform an action directly inside an array, whereas we otherwise would have to inline the variable and perform the conditions before constructing the array.