Skip to content

Implement PSR-20 ClockInterface on all clocks - #132

Closed
joelbutcher wants to merge 1 commit into
brick:mainfrom
joelbutcher:psr-20-clock
Closed

joelbutcher wants to merge 1 commit into
brick:mainfrom
joelbutcher:psr-20-clock

Conversation

@joelbutcher

Copy link
Copy Markdown
Contributor

Summary

Clock now extends PSR-20 Psr\Clock\ClockInterface, so every built-in clock can be used anywhere a PSR clock is expected.

  • All clocks implement now(): DateTimeImmutable. Native dates only hold microseconds, so nanoseconds are rounded down, just as ZonedDateTime::toNativeDateTimeImmutable() does.
  • SystemClock and FixedClock accept an optional TimeZone for the dates returned by now(), defaulting to UTC.
  • OffsetClock and ScaleClock have no new parameter: now() uses their reference clock's time zone, so a wrapper can't disagree with the clock it wraps.
new SystemClock();                                   // now() in UTC
new SystemClock(TimeZone::parse('Europe/London'));   // now() in London time
new OffsetClock(new SystemClock(TimeZone::parse('Europe/London')), $offset); // London too

Why UTC and not the PHP default time zone?

The time zone only changes the wall-clock fields of the returned date. The moment is the same either way, so timestamps, comparisons and differences don't depend on it. This library never reads date_default_timezone_get(); every now() that returns local fields asks for an explicit TimeZone. Defaulting to UTC keeps the new method in line with that. Apps that want local wall-clock output can pass a zone.

Breaking changes

  • Custom Clock implementations must now implement now().
  • New runtime dependency: psr/clock ^1.0.

Trade-off

To find its zone, a decorator clock calls its reference clock's now(). For SystemClock that reads the system time a second time, but only the zone from that call is used. An alternative would be a getTimeZone() on the clocks. Happy to switch if you prefer that.

Tests

  • New now() tests for each clock, with expected values worked out by hand: the UTC default, an explicit zone on the leaf clocks, and the zone inherited by the decorators.
  • Full suite passes (7861 tests); PHPStan and ECS are clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_011ogebQW2VgoLNsRLse8AFX

Clock now extends Psr\Clock\ClockInterface, so every built-in clock
implements now(), returning a DateTimeImmutable (microsecond precision).

SystemClock and FixedClock accept an optional TimeZone for now(),
defaulting to UTC so behaviour stays independent of the PHP default
timezone. OffsetClock and ScaleClock use their reference clock's zone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ogebQW2VgoLNsRLse8AFX
@codecov

codecov Bot commented Sep 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.30%. Comparing base (66dab53) to head (10b277b).

Additional details and impacted files
@@            Coverage Diff            @@
##               main     #132   +/-   ##
=========================================
  Coverage     99.30%   99.30%           
- Complexity     1109     1114    +5     
=========================================
  Files            48       48           
  Lines          2445     2458   +13     
=========================================
+ Hits           2428     2441   +13     
  Misses           17       17           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@joelbutcher
joelbutcher marked this pull request as ready for review September 26, 2026 22:28
@BenMorel

Copy link
Copy Markdown
Member

Hi, I think that if we're going down this route, we should add a getTimeZone() method to the Clock interface. Java actually has the timezone in their Clock interface, too, so it may be time to revisit that decision.

Now, to stay consistent, methods like LocalDate::now() should probably no longer require the timezone to be passed, since the clock provides it. But I know that the library requiring a timezone to be passed explicitly was actually deemed a useful feature (see this comment by @solodkiy for example).

One possible way to solve this could be to make the Clock mandatory in now() methods. That would be good for testability (always injecting a Clock) and would avoid global state (DefaultClock), but it may hurt usability.

Thoughts?

@solodkiy

solodkiy commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Maybe we should deprecate
LocalDate::now() entirely and add a set of methods like ->getLocalDate() to Clock?
I think this better serves the proposed approach.

@BenMorel

Copy link
Copy Markdown
Member

@solodkiy Thank you for your feedback.

I personally think that adding everything to the Clock interface bloats it too much, but we could provide something like a CurrentTimeService class that accepts a Clock and has methods like localDate(), localTime() etc.

But I'm not sure if it helps at all; which reads best?

$this->clock->localDate();

$this->currentTimeService->localDate();

LocalDate::now($this->clock);

I personally think that the last one is fine.

What's important I think is to keep the ability to explicitly provide a time zone when calling now() methods; maybe we should provide a way to override the timezone in Clock? Something like:

LocalDate::now($this->clock->withTimeZone('Europe/Paris'));

I'd also appreciate feedback from @zjbarg, @nkamuo, @brunocassol here, as you've all been involved in Clock / now() discussions in #111 and #113.

@joelbutcher

joelbutcher commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@BenMorel a couple of thoughts, if you don't mind:

  1. Java 17 actually separated their Clock from timezone entirely, by splitting on java.time.InstantSource and making Clock implement it (the interested method being default Clock withZone(ZoneId) . We could do something similar here, though Clock::getTime(): Instant already works like this.

  2. Having explicit timezones are one of the strengths of this library, which is one of the reasons we have adopted it at work. LocalDate::now($tz) makes you define which zone's "today" is being reached for. Adding zones to a clock, hides that dependency inside an injected dependency; arguably bad programming practice IMO

  3. Making Clock an explicit requirement for ::now() is a breaking change and DefaultClock would become dead weight, since freeze()/travelTo() only work through the implicit fallback in Instant::now(). Tests that rely on them would have to
    ▎ move to injected clocks.

  4. This PR introduces it's own BC problem; user-land implementations of Clock will break upon release, so this change should already target the next major version and be fully documented as such.


One suggestion could be to provide PSR adapters for the existing Clock implementations:

final class PsrClock implements \Psr\Clock\ClockInterface
{
    public function __construct(
        private readonly Clock $clock,
        private readonly TimeZone $timeZone,
    ) {}

    public function now(): DateTimeImmutable
    {
        return $this->clock->getTime()->atTimeZone($this->timeZone)->toNativeDateTimeImmutable();
    }
}


final class FromPsrClock implements Clock
{
    public function __construct(private readonly \Psr\Clock\ClockInterface $clock) {}

    public function getTime(): Instant
    {
        return ZonedDateTime::fromNativeDateTime($this->clock->now())->getInstant();
    }
}

@BenMorel

Copy link
Copy Markdown
Member

@joelbutcher Thank you for your feedback.

Java 17 actually separated their Clock from timezone entirely, by splitting on java.time.InstantSource and making Clock implement it (the interested method being default Clock withZone(ZoneId) . We could do something similar here, though Clock::getTime(): Instant already works like this.

I also came across Noda Time, which has 2 clocks: Clock and ZonedClock. I find the idea really interesting.

To get the current date, you either start from a Clock (which provides an Instant only) and provide the timezone yourself:

LocalDate today = clock.GetCurrentInstant().InZone(zone).Date;

Or get it from a ZonedClock, which holds a timezone:

LocalDate today = zonedClock.GetCurrentDate();

Just like Java, you can convert a Clock to a ZonedClock by calling InZone():

ZonedClock zonedClock = clock.InZone(zone);

What I like about this idea of splitting the Clock in two is that it accommodates both types of applications: those that only ever deal with a single timezone (inject a ZonedClock), and those that deal with multiple timezones (inject a Clock and apply the timezone each time).

They do have the "bloated" ZonedClock API that I complained about earlier, but it fits your intuition, @solodkiy; I may relax my point of view here.

Having explicit timezones are one of the strengths of this library, which is one of the reasons we have adopted it at work. LocalDate::now($tz) makes you define which zone's "today" is being reached for. Adding zones to a clock, hides that dependency inside an injected dependency; arguably bad programming practice IMO

Agreed, and I am a bit afraid of making the timezone any less mandatory. If we follow the above, though, and make SystemClock implement Clock and not ZonedClock, I believe we can keep forcing the user to always provide the timezone in one way or another.

Making Clock an explicit requirement for ::now() is a breaking change and DefaultClock would become dead weight, since freeze()/travelTo() only work through the implicit fallback in Instant::now(). Tests that rely on them would have to move to injected clocks.

I have on my agenda to remove DefaultClock though, I think it's a footgun that can allow spooky action at a distance; I'm torn between making it always mandatory (you always start from the Clock), or defaulting to SystemClock if not provided.

This PR introduces it's own BC problem; user-land implementations of Clock will break upon release, so this change should already target the next major version and be fully documented as such.

Breaking changes are absolutely not a problem before 1.0, now is the time to break things!

@joelbutcher

joelbutcher commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@BenMorel Could we treat the direction of Clock and ZonedClock different from adding PSR-20 support then? I'd be in favour of splitting the two and would be happy to contribute this myself, but cautious that we don't want to bloat this PR beyond the PSR capability today.

@joelbutcher

Copy link
Copy Markdown
Contributor Author

Closing in favour of #133, which follows the direction we landed on here:

  • Clock stays instant-only, and a new ZonedClock (à la Noda Time) wraps a Clock and a TimeZone, and implements PSR-20.
  • now() methods take a single ZonedClock: LocalDate::now($this->clock), as @BenMorel suggested, while the time zone stays mandatory, since a ZonedClock can't exist without one (keeping what @solodkiy and @brunocassol valued in LocalDate::utc() method #111/LocalDate::now($timezone /*= system TimeZone*/) #113).
  • PSR-20 lives on ZonedClock rather than on every clock, so SystemClock/FixedClock no longer need a time zone, and the decorator clocks no longer read their reference clock twice.

The approach changed enough that a fresh PR is easier to review than rewriting this one. Breaking changes are called out there; per Ben, now is the time to break things!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants