diff --git a/composer.json b/composer.json index a8e5d8bfb735f..d50dce4fcf708 100644 --- a/composer.json +++ b/composer.json @@ -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", diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index c6b5ea70484a1..ca52152c44186 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -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; @@ -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; @@ -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); diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.php b/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.php index 8845e5040766a..511e0a01d1641 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.php +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.php @@ -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; @@ -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() @@ -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') diff --git a/src/Symfony/Component/Clock/.gitattributes b/src/Symfony/Component/Clock/.gitattributes new file mode 100644 index 0000000000000..84c7add058fb5 --- /dev/null +++ b/src/Symfony/Component/Clock/.gitattributes @@ -0,0 +1,4 @@ +/Tests export-ignore +/phpunit.xml.dist export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore diff --git a/src/Symfony/Component/Clock/.gitignore b/src/Symfony/Component/Clock/.gitignore new file mode 100644 index 0000000000000..c49a5d8df5c65 --- /dev/null +++ b/src/Symfony/Component/Clock/.gitignore @@ -0,0 +1,3 @@ +vendor/ +composer.lock +phpunit.xml diff --git a/src/Symfony/Component/Clock/CHANGELOG.md b/src/Symfony/Component/Clock/CHANGELOG.md new file mode 100644 index 0000000000000..5ffa40eff75d9 --- /dev/null +++ b/src/Symfony/Component/Clock/CHANGELOG.md @@ -0,0 +1,7 @@ +CHANGELOG +========= + +6.2 +--- + + * Add the component diff --git a/src/Symfony/Component/Clock/ClockInterface.php b/src/Symfony/Component/Clock/ClockInterface.php new file mode 100644 index 0000000000000..af502a14ed6eb --- /dev/null +++ b/src/Symfony/Component/Clock/ClockInterface.php @@ -0,0 +1,24 @@ + + * + * 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 + */ +interface ClockInterface +{ + public function now(): \DateTimeImmutable; + + public function sleep(float|int $seconds): void; + + public function withTimeZone(\DateTimeZone|string $timezone): static; +} diff --git a/src/Symfony/Component/Clock/LICENSE b/src/Symfony/Component/Clock/LICENSE new file mode 100644 index 0000000000000..0ece8964f767d --- /dev/null +++ b/src/Symfony/Component/Clock/LICENSE @@ -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. diff --git a/src/Symfony/Component/Clock/MockClock.php b/src/Symfony/Component/Clock/MockClock.php new file mode 100644 index 0000000000000..08ac57b2c1d9c --- /dev/null +++ b/src/Symfony/Component/Clock/MockClock.php @@ -0,0 +1,67 @@ + + * + * 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 + */ +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; + } +} diff --git a/src/Symfony/Component/Clock/MonotonicClock.php b/src/Symfony/Component/Clock/MonotonicClock.php new file mode 100644 index 0000000000000..65f86e72a39fb --- /dev/null +++ b/src/Symfony/Component/Clock/MonotonicClock.php @@ -0,0 +1,81 @@ + + * + * 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 + */ +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; + } +} diff --git a/src/Symfony/Component/Clock/NativeClock.php b/src/Symfony/Component/Clock/NativeClock.php new file mode 100644 index 0000000000000..0fcf7879a2d9d --- /dev/null +++ b/src/Symfony/Component/Clock/NativeClock.php @@ -0,0 +1,55 @@ + + * + * 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 + */ +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; + } +} diff --git a/src/Symfony/Component/Clock/README.md b/src/Symfony/Component/Clock/README.md new file mode 100644 index 0000000000000..225ad371d7ef1 --- /dev/null +++ b/src/Symfony/Component/Clock/README.md @@ -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) diff --git a/src/Symfony/Component/Clock/Tests/MockClockTest.php b/src/Symfony/Component/Clock/Tests/MockClockTest.php new file mode 100644 index 0000000000000..56c76299a41c4 --- /dev/null +++ b/src/Symfony/Component/Clock/Tests/MockClockTest.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Clock\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Clock\MockClock; + +class MockClockTest extends TestCase +{ + public function testConstruct() + { + $clock = new MockClock(); + $this->assertSame('UTC', $clock->now()->getTimezone()->getName()); + + $tz = 'Europe/Paris'; + $clock = new MockClock($tz); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + + $clock = new MockClock('now', $tz); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + + $clock = new MockClock('now', new \DateTimeZone($tz)); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + + $now = new \DateTimeImmutable(); + $clock = new MockClock($now); + $this->assertEquals($now, $clock->now()); + + $clock = new MockClock('2022-06-20 00:00:00'); + $this->assertSame('2022-06-20 00:00:00', $clock->now()->format('Y-m-d H:i:s')); + } + + public function testNow() + { + $before = new \DateTimeImmutable(); + $clock = new MockClock(); + $after = new \DateTimeImmutable(); + + $this->assertGreaterThan($before, $clock->now()); + $this->assertLessThan($after, $clock->now()); + + $this->assertEquals($clock->now(), $clock->now()); + $this->assertNotSame($clock->now(), $clock->now()); + } + + public function testSleep() + { + $clock = new MockClock((new \DateTimeImmutable('@123.456'))->setTimezone(new \DateTimeZone('UTC'))); + $tz = $clock->now()->getTimezone()->getName(); + + $clock->sleep(4.999); + $this->assertSame('128.455000', $clock->now()->format('U.u')); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + } + + public function testWithTimeZone() + { + $clock = new MockClock(); + $utcClock = $clock->withTimeZone('UTC'); + + $this->assertNotSame($clock, $utcClock); + $this->assertSame('UTC', $utcClock->now()->getTimezone()->getName()); + } +} diff --git a/src/Symfony/Component/Clock/Tests/MonotonicClockTest.php b/src/Symfony/Component/Clock/Tests/MonotonicClockTest.php new file mode 100644 index 0000000000000..c4d49d1b321ee --- /dev/null +++ b/src/Symfony/Component/Clock/Tests/MonotonicClockTest.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Clock\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Clock\MonotonicClock; + +class MonotonicClockTest extends TestCase +{ + public function testConstruct() + { + $clock = new MonotonicClock('UTC'); + $this->assertSame('UTC', $clock->now()->getTimezone()->getName()); + + $tz = date_default_timezone_get(); + $clock = new MonotonicClock(); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + + $clock = new MonotonicClock(new \DateTimeZone($tz)); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + } + + public function testNow() + { + $clock = new MonotonicClock(); + $before = new \DateTimeImmutable(); + usleep(10); + $now = $clock->now(); + usleep(10); + $after = new \DateTimeImmutable(); + + $this->assertGreaterThan($before, $now); + $this->assertLessThan($after, $now); + } + + public function testSleep() + { + $clock = new MonotonicClock(); + $tz = $clock->now()->getTimezone()->getName(); + + $before = microtime(true); + $clock->sleep(1.5); + $now = (float) $clock->now()->format('U.u'); + usleep(10); + $after = microtime(true); + + $this->assertGreaterThan($before + 1.5, $now); + $this->assertLessThan($after, $now); + $this->assertLessThan(1.9, $now - $before); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + } + + public function testWithTimeZone() + { + $clock = new MonotonicClock(); + $utcClock = $clock->withTimeZone('UTC'); + + $this->assertNotSame($clock, $utcClock); + $this->assertSame('UTC', $utcClock->now()->getTimezone()->getName()); + } +} diff --git a/src/Symfony/Component/Clock/Tests/NativeClockTest.php b/src/Symfony/Component/Clock/Tests/NativeClockTest.php new file mode 100644 index 0000000000000..c8983e15972fb --- /dev/null +++ b/src/Symfony/Component/Clock/Tests/NativeClockTest.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Clock\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Clock\NativeClock; + +class NativeClockTest extends TestCase +{ + public function testConstruct() + { + $clock = new NativeClock('UTC'); + $this->assertSame('UTC', $clock->now()->getTimezone()->getName()); + + $tz = date_default_timezone_get(); + $clock = new NativeClock(); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + + $clock = new NativeClock(new \DateTimeZone($tz)); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + } + + public function testNow() + { + $clock = new NativeClock(); + $before = new \DateTimeImmutable(); + usleep(10); + $now = $clock->now(); + usleep(10); + $after = new \DateTimeImmutable(); + + $this->assertGreaterThan($before, $now); + $this->assertLessThan($after, $now); + } + + public function testSleep() + { + $clock = new NativeClock(); + $tz = $clock->now()->getTimezone()->getName(); + + $before = microtime(true); + $clock->sleep(1.5); + $now = (float) $clock->now()->format('U.u'); + usleep(10); + $after = microtime(true); + + $this->assertGreaterThan($before + 1.5, $now); + $this->assertLessThan($after, $now); + $this->assertLessThan(1.9, $now - $before); + $this->assertSame($tz, $clock->now()->getTimezone()->getName()); + } + + public function testWithTimeZone() + { + $clock = new NativeClock(); + $utcClock = $clock->withTimeZone('UTC'); + + $this->assertNotSame($clock, $utcClock); + $this->assertSame('UTC', $utcClock->now()->getTimezone()->getName()); + } +} diff --git a/src/Symfony/Component/Clock/composer.json b/src/Symfony/Component/Clock/composer.json new file mode 100644 index 0000000000000..897d57f4b307a --- /dev/null +++ b/src/Symfony/Component/Clock/composer.json @@ -0,0 +1,28 @@ +{ + "name": "symfony/clock", + "type": "library", + "description": "Decouples applications from the system clock", + "keywords": ["clock", "time", "psr20"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=8.1" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Clock\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev" +} diff --git a/src/Symfony/Component/Clock/phpunit.xml.dist b/src/Symfony/Component/Clock/phpunit.xml.dist new file mode 100644 index 0000000000000..06071b21d2f63 --- /dev/null +++ b/src/Symfony/Component/Clock/phpunit.xml.dist @@ -0,0 +1,30 @@ + + + + + + + + + + ./Tests/ + + + + + + ./ + + + ./Tests + ./vendor + + + 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