Last active
August 18, 2019 00:00
-
-
Save calebporzio/a5775e4c6a54fa8245126041b49669d0 to your computer and use it in GitHub Desktop.
A little Laravel helper function for hijacking Carbon's "now()" inside a callback
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
<?php | |
// Helper usage: | |
// timeTravel(Carbon::parse('one year ago'), function () {...}); | |
function timeTravel($target, $callback) { | |
Illuminate\Support\Carbon::setTestNow($target); | |
return tap($callback(), function () { | |
Illuminate\Support\Carbon::setTestNow(); | |
}); | |
} | |
// Macro usage: | |
// Carbon::parse('last year')->timeTravel(function() {...}}; | |
Illuminate\Support\Carbon::macro('timeTravel', function ($callback) { | |
$target = $this; | |
Illuminate\Support\Carbon::setTestNow($target); | |
return tap($callback(), function () { | |
Illuminate\Support\Carbon::setTestNow(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment