lcobucci / clock
Yet another clock abstraction
Installs: 123 838 507
Dependents: 96
Suggesters: 4
Security: 0
Stars: 711
Watchers: 5
Forks: 24
Open Issues: 1
Requires
- php: ~8.2.0 || ~8.3.0 || ~8.4.0
- psr/clock: ^1.0
Requires (Dev)
- infection/infection: ^0.29
- lcobucci/coding-standard: ^11.1.0
- phpstan/extension-installer: ^1.3.1
- phpstan/phpstan: ^1.10.25
- phpstan/phpstan-deprecation-rules: ^1.1.3
- phpstan/phpstan-phpunit: ^1.3.13
- phpstan/phpstan-strict-rules: ^1.5.1
- phpunit/phpunit: ^11.3.6
Provides
README
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:
<?php use Lcobucci\Clock\Clock; use Lcobucci\Clock\SystemClock; use Lcobucci\Clock\FrozenClock; function filterData(Clock $clock, array $objects): array { return array_filter( $objects, static function (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 = new SystemClock(new DateTimeZone('America/Sao_Paulo')); // Test object that always returns a fixed time object $clock = new FrozenClock( new DateTimeImmutable('2017-05-07 18:49:30') ); // Or creating a frozen clock from the current time on UTC // $clock = FrozenClock::fromUTC(); $objects = [ (object) ['expiresAt' => new DateTimeImmutable('2017-12-31 23:59:59')], (object) ['expiresAt' => new DateTimeImmutable('2017-06-30 23:59:59')], (object) ['expiresAt' => new DateTimeImmutable('2017-01-30 23:59:59')], ]; var_dump(filterData($clock, $objects)); // last item will be filtered