[9.x] Add Conditionable Trait to Illuminate\Support\Carbon#42500
Merged
taylorotwell merged 2 commits intoMay 25, 2022
Conversation
Contributor
|
I was just gonna make this PR... |
Member
|
I actually think the old way is so much cleaner here 😅 |
Contributor
Author
😅 There might be better examples, where it's more of an improvement. This is just rather simplified, as everyone knows how the Conditionable works :) How about this? $carbon = Carbon::now()
->when($filter, fn (Carbon $carbon) => $carbon->setIsoDate(...$filter))
->startOfWeek();
// Versus
$carbon = $filter
? Carbon::now()->setIsoDate(...$filter)->startOfWeek()
: Carbon::now()->startOfWeek();
// Or ...
$carbon = Carbon::now()
->when($filter)->setIsoDate(...$filter)
->startOfWeek();It's just that I prefer closures over proxies, because it's annoying to lose autocompletion. |
chu121su12
pushed a commit
to chu121su12/framework
that referenced
this pull request
May 26, 2022
…2500) * Make Carbon conditionable * Style
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Today I had a situation where I needed to set the week-number of a Carbon date, but only when a user selected a filter. Otherwise the Carbon instance should default to the current time.
I think that many developers as well have had the situation where they wanted to conditionably apply a method to a Carbon object. At least, I've had this feeling multiple times previously.
I could've done this with an
if-condition, but I really missed the elegance of using the->when()method from the Conditionable, so this looked like the perfect situation for adding the Conditionable trait.Simple example
I hope this will be useful to many developers!