Skip to content

Repository files navigation

Clock

Total DownloadsLatest Stable VersionUnstable Version

Build StatusCode Coverage

Yet another clock abstraction...

The purpose is to decouple projects from DateTimeImmutable instantiation so that we can test things properly.

Installation

Package is available on Packagist, you can install it using Composer.

composer require lcobucci/clock

Usage

Make your objects depend on the Lcobucci\Clock\Clock interface and use SystemClock or FrozenClock to retrieve the current time or a specific time (for testing), respectively:

<?phpuseLcobucci\Clock\Clock;
useLcobucci\Clock\SystemClock;
useLcobucci\Clock\FrozenClock;
functionfilterData(Clock$clock, array$objects): array
{
returnarray_filter(
$objects,
staticfunction (stdClass$object) use ($clock): bool {
return$object->expiresAt > $clock->now();
}
);
}
// Object that will return the current time based on the given timezone// $clock = SystemClock::fromSystemTimezone();// $clock = SystemClock::fromUTC();$clock = newSystemClock(newDateTimeZone('America/Sao_Paulo'));
// Test object that always returns a fixed time object$clock = newFrozenClock(
newDateTimeImmutable('2017-05-07 18:49:30')
);
// Or creating a frozen clock from the current time on UTC// $clock = FrozenClock::fromUTC();$objects = [
(object) ['expiresAt' => newDateTimeImmutable('2017-12-31 23:59:59')],
(object) ['expiresAt' => newDateTimeImmutable('2017-06-30 23:59:59')],
(object) ['expiresAt' => newDateTimeImmutable('2017-01-30 23:59:59')],
];
var_dump(filterData($clock, $objects)); // last item will be filtered

About

Yet another clock abstraction

Topics

Resources

Stars

799 stars

Watchers

3 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages