lcobucci/clock

又一个时钟抽象

资助包维护!
lcobucci
Patreon

安装次数: 110,618,686

依赖: 93

建议者: 4

安全: 0

星标: 682

关注者: 6

分支: 23

开放问题: 3

3.2.0 2023-11-17 17:00 UTC

README

Total Downloads Latest Stable Version Unstable Version

Build Status Code Coverage

又一个时钟抽象...

目的是将项目从 DateTimeImmutable 实例化中解耦,以便我们可以正确地进行测试。

安装

此包可在 Packagist 上找到,您可以使用 Composer 进行安装。

composer require lcobucci/clock

用法

使您的对象依赖于 Lcobucci\Clock\Clock 接口,并分别使用 SystemClockFrozenClock 获取当前时间或特定时间(用于测试)。

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