Skip to content

Instantly share code, notes, and snippets.

@calebporzio
Last active August 18, 2019 00:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save calebporzio/a5775e4c6a54fa8245126041b49669d0 to your computer and use it in GitHub Desktop.
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
<?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