Skip to content

Instantly share code, notes, and snippets.

@oliuz
Forked from calebporzio/time_travel_helper.php
Created August 18, 2019 00:00
Show Gist options
  • Save oliuz/183b27947d1209a15814db95595d7592 to your computer and use it in GitHub Desktop.
Save oliuz/183b27947d1209a15814db95595d7592 to your computer and use it in GitHub Desktop.
A little Laravel helper function for hijacking Carbon's "now()" inside a callback
<?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