Yet another clock abstraction
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
src
test
.gitattributes
.gitignore
.scrutinizer.yml
.travis.yml
LICENSE
README.md
composer.json
infection.json.dist
phpcs.xml.dist
phpstan.neon.dist
phpunit.xml.dist

README.md

Clock

Total Downloads Latest Stable Version

Branch master Build Status Scrutinizer Code Quality Code Coverage SensioLabsInsight

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

Basic usage

Simply have 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,
        function (stdClass $object) use ($clock): bool {
            return $object->expiresAt > $clock->now();
        }
    );
}

// Object that will return the current time based on the given timezone
$clock = new SystemClock(new DateTimeZone('UTC'));

// Test object that always returns a fixed time object
$clock = new FrozenClock(
    new DateTimeImmutable('2017-05-07 18:49:30')
);

$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