Skip to content

lcobucci/clock

Folders and files

NameName
Last commit message
Last commit date
Mar 19, 2025
Sep 24, 2024
Sep 24, 2024
Mar 1, 2023
Feb 17, 2023
May 7, 2017
Feb 17, 2023
Sep 24, 2024
Feb 11, 2025
Mar 26, 2025
Aug 27, 2020
Oct 5, 2020
Sep 24, 2024
Sep 24, 2024
Nov 5, 2022

Repository files navigation

Clock

Total Downloads Latest Stable Version Unstable Version

Build Status Code 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:

<?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