Skip to content

[Clock] A new component to decouple applications from the system clock #46715

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"symfony/asset": "self.version",
"symfony/browser-kit": "self.version",
"symfony/cache": "self.version",
"symfony/clock": "self.version",
"symfony/config": "self.version",
"symfony/console": "self.version",
"symfony/css-selector": "self.version",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Container\ContainerInterface as PsrContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Log\LoggerAwareInterface;
use Symfony\Bridge\Monolog\Processor\DebugProcessor;
Expand All @@ -40,6 +39,7 @@
use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderInterface;
Expand Down Expand Up @@ -273,8 +273,9 @@ public function load(array $configs, ContainerBuilder $container)
$loader->load('fragment_renderer.php');
$loader->load('error_renderer.php');

if (ContainerBuilder::willBeAvailable('psr/event-dispatcher', PsrEventDispatcherInterface::class, ['symfony/framework-bundle'])) {
$container->setAlias(PsrEventDispatcherInterface::class, 'event_dispatcher');
if (!ContainerBuilder::willBeAvailable('symfony/clock', ClockInterface::class, ['symfony/framework-bundle'])) {
$container->removeDefinition('clock');
$container->removeAlias(ClockInterface::class);
}

$container->registerAliasForArgument('parameter_bag', PsrContainerInterface::class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;
use Symfony\Bundle\FrameworkBundle\CacheWarmer\ConfigBuilderCacheWarmer;
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Clock\NativeClock;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\SelfCheckingResourceChecker;
use Symfony\Component\Config\ResourceCheckerConfigCacheFactory;
Expand Down Expand Up @@ -77,6 +80,7 @@ class_exists(WorkflowEvents::class) ? WorkflowEvents::ALIASES : []
->tag('event_dispatcher.dispatcher', ['name' => 'event_dispatcher'])
->alias(EventDispatcherInterfaceComponentAlias::class, 'event_dispatcher')
->alias(EventDispatcherInterface::class, 'event_dispatcher')
->alias(PsrEventDispatcherInterface::class, 'event_dispatcher')

->set('http_kernel', HttpKernel::class)
->public()
Expand Down Expand Up @@ -223,6 +227,9 @@ class_exists(WorkflowEvents::class) ? WorkflowEvents::ALIASES : []
->args([service(KernelInterface::class), service('logger')->nullOnInvalid()])
->tag('kernel.cache_warmer')

->set('clock', NativeClock::class)
->alias(ClockInterface::class, 'clock')

// register as abstract and excluded, aka not-autowirable types
->set(LoaderInterface::class)->abstract()->tag('container.excluded')
->set(Request::class)->abstract()->tag('container.excluded')
Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/Clock/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/Tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
3 changes: 3 additions & 0 deletions src/Symfony/Component/Clock/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml
7 changes: 7 additions & 0 deletions src/Symfony/Component/Clock/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CHANGELOG
=========

6.2
---

* Add the component
24 changes: 24 additions & 0 deletions src/Symfony/Component/Clock/ClockInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Clock;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ClockInterface
{
public function now(): \DateTimeImmutable;

public function sleep(float|int $seconds): void;

public function withTimeZone(\DateTimeZone|string $timezone): static;
}
19 changes: 19 additions & 0 deletions src/Symfony/Component/Clock/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2022 Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
67 changes: 67 additions & 0 deletions src/Symfony/Component/Clock/MockClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Clock;

/**
* A clock that always returns the same date, suitable for testing time-sensitive logic.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class MockClock implements ClockInterface
{
private \DateTimeImmutable $now;

public function __construct(\DateTimeImmutable|string $now = 'now', \DateTimeZone|string $timezone = null)
{
if (\is_string($timezone)) {
$timezone = new \DateTimeZone($timezone);
}

if (\is_string($now)) {
$now = new \DateTimeImmutable($now, $timezone ?? new \DateTimeZone('UTC'));
}

$this->now = null !== $timezone ? $now->setTimezone($timezone) : $now;
}

public function now(): \DateTimeImmutable
{
return clone $this->now;
}

public function sleep(float|int $seconds): void
{
$now = explode('.', $this->now->format('U.u'));

if (0 < $s = (int) $seconds) {
$now[0] += $s;
}

if (0 < ($us = $seconds - $s) && 1E6 <= $now[1] += $us * 1E6) {
++$now[0];
$now[1] -= 1E6;
}

$datetime = '@'.$now[0].'.'.str_pad($now[1], 6, '0', \STR_PAD_LEFT);
$timezone = $this->now->getTimezone();

$this->now = (new \DateTimeImmutable($datetime, $timezone))->setTimezone($timezone);
}

public function withTimeZone(\DateTimeZone|string $timezone): static
{
$clone = clone $this;
$clone->now = $clone->now->setTimezone(\is_string($timezone) ? new \DateTimeZone($timezone) : $timezone);

return $clone;
}
}
81 changes: 81 additions & 0 deletions src/Symfony/Component/Clock/MonotonicClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Clock;

/**
* A monotonic clock suitable for performance profiling.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class MonotonicClock implements ClockInterface
{
private int $sOffset;
private int $usOffset;
private \DateTimeZone $timezone;

public function __construct(\DateTimeZone|string $timezone = null)
{
if (false === $offset = hrtime()) {
throw new \RuntimeException('hrtime() returned false: the runtime environment does not provide access to a monotonic timer.');
}

$time = gettimeofday();
$this->sOffset = $time['sec'] - $offset[0];
$this->usOffset = $time['usec'] - (int) ($offset[1] / 1000);

if (\is_string($timezone ??= date_default_timezone_get())) {
$this->timezone = new \DateTimeZone($timezone);
} else {
$this->timezone = $timezone;
}
}

public function now(): \DateTimeImmutable
{
[$s, $us] = hrtime();

if (1000000 <= $us = (int) ($us / 1000) + $this->usOffset) {
++$s;
$us -= 1000000;
} elseif (0 > $us) {
--$s;
$us += 1000000;
}

if (6 !== \strlen($now = (string) $us)) {
$now = str_pad($now, 6, '0', \STR_PAD_LEFT);
}

$now = '@'.($s + $this->sOffset).'.'.$now;

return (new \DateTimeImmutable($now, $this->timezone))->setTimezone($this->timezone);
}

public function sleep(float|int $seconds): void
{
if (0 < $s = (int) $seconds) {
sleep($s);
}

if (0 < $us = $seconds - $s) {
usleep($us * 1E6);
}
}

public function withTimeZone(\DateTimeZone|string $timezone): static
{
$clone = clone $this;
$clone->timezone = \is_string($timezone) ? new \DateTimeZone($timezone) : $timezone;

return $clone;
}
}
55 changes: 55 additions & 0 deletions src/Symfony/Component/Clock/NativeClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Clock;

/**
* A clock that relies the system time.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class NativeClock implements ClockInterface
{
private \DateTimeZone $timezone;

public function __construct(\DateTimeZone|string $timezone = null)
{
if (\is_string($timezone ??= date_default_timezone_get())) {
$this->timezone = new \DateTimeZone($timezone);
} else {
$this->timezone = $timezone;
}
}

public function now(): \DateTimeImmutable
{
return new \DateTimeImmutable('now', $this->timezone);
}

public function sleep(float|int $seconds): void
{
if (0 < $s = (int) $seconds) {
sleep($s);
}

if (0 < $us = $seconds - $s) {
usleep($us * 1E6);
}
}

public function withTimeZone(\DateTimeZone|string $timezone): static
{
$clone = clone $this;
$clone->timezone = \is_string($timezone) ? new \DateTimeZone($timezone) : $timezone;

return $clone;
}
}
47 changes: 47 additions & 0 deletions src/Symfony/Component/Clock/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Clock Component
===============

Symfony Clock decouples applications from the system clock.

Getting Started
---------------

```
$ composer require symfony/clock
```

```php
use Symfony\Component\Clock\NativeClock;
use Symfony\Component\Clock\ClockInterface;

class MyClockSensitiveClass
{
public function __construct(
private ClockInterface $clock,
) {
// Only if you need to force a timezone:
//$this->clock = $clock->withTimeZone('UTC');
}

public function doSomething()
{
$now = $this->clock->now();
// [...] do something with $now, which is a \DateTimeImmutable object

$this->clock->sleep(2.5); // Pause execution for 2.5 seconds
}
}

$clock = new NativeClock();
$service = new MyClockSensitiveClass($clock);
$service->doSomething();
```

Resources
---------

* [Documentation](https://symfony.com/doc/current/clock.html)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy