Skip to content

Ban DateTime from the codebase #47730

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
Oct 9, 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
8 changes: 4 additions & 4 deletions src/Symfony/Component/BrowserKit/Cookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public function __construct(string $name, ?string $value, string $expires = null
$this->samesite = $samesite;

if (null !== $expires) {
$timestampAsDateTime = \DateTime::createFromFormat('U', $expires);
$timestampAsDateTime = \DateTimeImmutable::createFromFormat('U', $expires);
if (false === $timestampAsDateTime) {
throw new \UnexpectedValueException(sprintf('The cookie expiration time "%s" is not valid.', $expires));
}
Expand All @@ -89,7 +89,7 @@ public function __toString(): string
$cookie = sprintf('%s=%s', $this->name, $this->rawValue);

if (null !== $this->expires) {
$dateTime = \DateTime::createFromFormat('U', $this->expires, new \DateTimeZone('GMT'));
$dateTime = \DateTimeImmutable::createFromFormat('U', $this->expires, new \DateTimeZone('GMT'));
$cookie .= '; expires='.str_replace('+0000', '', $dateTime->format(self::DATE_FORMATS[0]));
}

Expand Down Expand Up @@ -202,13 +202,13 @@ private static function parseDate(string $dateValue): ?string
}

foreach (self::DATE_FORMATS as $dateFormat) {
if (false !== $date = \DateTime::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) {
if (false !== $date = \DateTimeImmutable::createFromFormat($dateFormat, $dateValue, new \DateTimeZone('GMT'))) {
return $date->format('U');
}
}

// attempt a fallback for unusual formatting
if (false !== $date = date_create($dateValue, new \DateTimeZone('GMT'))) {
if (false !== $date = date_create_immutable($dateValue, new \DateTimeZone('GMT'))) {
return $date->format('U');
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Adapter/ChainAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ static function ($sourceItem, $item, $defaultLifetime, $sourceMetadata = null) {
$item->metadata = $item->newMetadata = $sourceItem->metadata = $sourceMetadata;

if (isset($item->metadata[CacheItem::METADATA_EXPIRY])) {
$item->expiresAt(\DateTime::createFromFormat('U.u', sprintf('%.6F', $item->metadata[CacheItem::METADATA_EXPIRY])));
$item->expiresAt(\DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', $item->metadata[CacheItem::METADATA_EXPIRY])));
} elseif (0 < $defaultLifetime) {
$item->expiresAfter($defaultLifetime);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static function normalizeDuration(string $duration): int
}

try {
return \DateTime::createFromFormat('U', 0)->add(new \DateInterval($duration))->getTimestamp();
return \DateTimeImmutable::createFromFormat('U', 0)->add(new \DateInterval($duration))->getTimestamp();
} catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('Cannot parse date interval "%s".', $duration), 0, $e);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Adapter/ProxyAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ static function ($key, $innerItem, $poolHash) {
self::$setInnerItem ??= \Closure::bind(
static function (CacheItemInterface $innerItem, CacheItem $item, $expiry = null) {
$innerItem->set($item->pack());
$innerItem->expiresAt(($expiry ?? $item->expiry) ? \DateTime::createFromFormat('U.u', sprintf('%.6F', $expiry ?? $item->expiry)) : null);
$innerItem->expiresAt(($expiry ?? $item->expiry) ? \DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', $expiry ?? $item->expiry)) : null);
},
null,
CacheItem::class
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/CacheItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function expiresAfter(mixed $time): static
if (null === $time) {
$this->expiry = null;
} elseif ($time instanceof \DateInterval) {
$this->expiry = microtime(true) + \DateTime::createFromFormat('U', 0)->add($time)->format('U.u');
$this->expiry = microtime(true) + \DateTimeImmutable::createFromFormat('U', 0)->add($time)->format('U.u');
} elseif (\is_int($time)) {
$this->expiry = $time + microtime(true);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Console/Logger/ConsoleLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ private function interpolate(string $message, array $context): string
if (null === $val || \is_scalar($val) || $val instanceof \Stringable) {
$replacements["{{$key}}"] = $val;
} elseif ($val instanceof \DateTimeInterface) {
$replacements["{{$key}}"] = $val->format(\DateTime::RFC3339);
$replacements["{{$key}}"] = $val->format(\DateTimeInterface::RFC3339);
} elseif (\is_object($val)) {
$replacements["{{$key}}"] = '[object '.$val::class.']';
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public function testContextCanContainAnything()
'int' => 0,
'float' => 0.5,
'nested' => ['with object' => new DummyTest()],
'object' => new \DateTime(),
'object' => new \DateTimeImmutable(),
'resource' => fopen('php://memory', 'r'),
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -497,12 +497,12 @@ public function testProcessFactoryCallbackSuccessOnValidType()
{
$container = new ContainerBuilder();

$container->register('bar', \DateTime::class)
->setFactory('date_create');
$container->register('bar', \DateTimeImmutable::class)
->setFactory('date_create_immutable');

(new CheckTypeDeclarationsPass(true))->process($container);

$this->assertInstanceOf(\DateTime::class, $container->get('bar'));
$this->assertInstanceOf(\DateTimeImmutable::class, $container->get('bar'));
}

public function testProcessDoesNotLoadCodeByDefault()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function provideInvalidClassId()
{
yield [\stdClass::class];
yield ['bar'];
yield [\DateTime::class];
yield [\DateTimeImmutable::class];
}

public function testNonFqcnChildDefinition()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1296,20 +1296,20 @@ public function testClassFromId()
public function testNoClassFromGlobalNamespaceClassId()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('The definition for "DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.');
$this->expectExceptionMessage('The definition for "DateTimeImmutable" has no class attribute, and appears to reference a class or interface in the global namespace.');
$container = new ContainerBuilder();

$container->register(\DateTime::class);
$container->register(\DateTimeImmutable::class);
$container->compile();
}

public function testNoClassFromGlobalNamespaceClassIdWithLeadingSlash()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('The definition for "\DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.');
$this->expectExceptionMessage('The definition for "\DateTimeImmutable" has no class attribute, and appears to reference a class or interface in the global namespace.');
$container = new ContainerBuilder();

$container->register('\\'.\DateTime::class);
$container->register('\\'.\DateTimeImmutable::class);
$container->compile();
}

Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/ErrorHandler/BufferingLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function __destruct()
if (null === $val || \is_scalar($val) || (\is_object($val) && \is_callable([$val, '__toString']))) {
$message = str_replace("{{$key}}", $val, $message);
} elseif ($val instanceof \DateTimeInterface) {
$message = str_replace("{{$key}}", $val->format(\DateTime::RFC3339), $message);
$message = str_replace("{{$key}}", $val->format(\DateTimeInterface::RFC3339), $message);
} elseif (\is_object($val)) {
$message = str_replace("{{$key}}", '[object '.get_debug_type($val).']', $message);
} else {
Expand All @@ -62,7 +62,7 @@ public function __destruct()
}
}

error_log(sprintf('%s [%s] %s', date(\DateTime::RFC3339), $level, $message));
error_log(sprintf('%s [%s] %s', date(\DateTimeInterface::RFC3339), $level, $message));
}
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Component/Finder/Comparator/DateComparator.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function __construct(string $test)
}

try {
$date = new \DateTime($matches[2]);
$date = new \DateTimeImmutable($matches[2]);
$target = $date->format('U');
} catch (\Exception) {
throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2]));
Expand Down
8 changes: 4 additions & 4 deletions src/Symfony/Component/HttpFoundation/Tests/ResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -796,17 +796,17 @@ public function testIsImmutable()
public function testSetDate()
{
$response = new Response();
$response->setDate(\DateTime::createFromFormat(\DateTime::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));
$response->setDate(\DateTime::createFromFormat(\DateTimeInterface::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));

$this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTime::ATOM));
$this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTimeInterface::ATOM));
}

public function testSetDateWithImmutable()
{
$response = new Response();
$response->setDate(\DateTimeImmutable::createFromFormat(\DateTime::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));
$response->setDate(\DateTimeImmutable::createFromFormat(\DateTimeInterface::ATOM, '2013-01-26T09:21:56+0100', new \DateTimeZone('Europe/Berlin')));

$this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTime::ATOM));
$this->assertEquals('2013-01-26T08:21:56+00:00', $response->getDate()->format(\DateTimeInterface::ATOM));
}

public function testSetExpires()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ public function setKernel(KernelInterface $kernel = null)

public function collect(Request $request, Response $response, \Throwable $exception = null)
{
$eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE);
$eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE);
$eom = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE);
$eol = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE);

$this->data = [
'token' => $response->headers->get('X-Debug-Token'),
Expand Down Expand Up @@ -244,9 +244,9 @@ public function getName(): string

private function determineSymfonyState(): string
{
$now = new \DateTime();
$eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->modify('last day of this month');
$eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->modify('last day of this month');
$now = new \DateTimeImmutable();
$eom = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->modify('last day of this month');
$eol = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->modify('last day of this month');

if ($now > $eol) {
$versionState = 'eol';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public function onKernelResponse(ResponseEvent $event)

if ($autoCacheControl) {
$response
->setExpires(new \DateTime())
->setExpires(new \DateTimeImmutable())
->setPrivate()
->setMaxAge(0)
->headers->addCacheControlDirective('must-revalidate');
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,7 @@ protected function forward(Request $request, bool $catch = false, Response $entr
Anyway, a client that received a message without a "Date" header MUST add it.
*/
if (!$response->headers->has('Date')) {
$response->setDate(\DateTime::createFromFormat('U', time()));
$response->setDate(\DateTimeImmutable::createFromFormat('U', time()));
}

$this->processResponseBody($request, $response);
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/HttpKernel/Log/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ private function format(string $level, string $message, array $context, bool $pr
if (null === $val || \is_scalar($val) || $val instanceof \Stringable) {
$replacements["{{$key}}"] = $val;
} elseif ($val instanceof \DateTimeInterface) {
$replacements["{{$key}}"] = $val->format(\DateTime::RFC3339);
$replacements["{{$key}}"] = $val->format(\DateTimeInterface::RFC3339);
} elseif (\is_object($val)) {
$replacements["{{$key}}"] = '[object '.$val::class.']';
} else {
Expand All @@ -108,7 +108,7 @@ private function format(string $level, string $message, array $context, bool $pr

$log = sprintf('[%s] %s', $level, $message).\PHP_EOL;
if ($prefixDate) {
$log = date(\DateTime::RFC3339).' '.$log;
$log = date(\DateTimeInterface::RFC3339).' '.$log;
}

return $log;
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpKernel/Profiler/Profiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ private function getTimestamp(?string $value): ?int
}

try {
$value = new \DateTime(is_numeric($value) ? '@'.$value : $value);
$value = new \DateTimeImmutable(is_numeric($value) ? '@'.$value : $value);
} catch (\Exception) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@ public function testFullDate(string $timezone)
date_default_timezone_set($timezone);
$resolver = new DateTimeValueResolver();

$argument = new ArgumentMetadata('dummy', \DateTime::class, false, false, null);
$argument = new ArgumentMetadata('dummy', \DateTimeImmutable::class, false, false, null);
$request = self::requestWithAttributes(['dummy' => '2012-07-21 00:00:00']);

$results = $resolver->resolve($request, $argument);

$this->assertCount(1, $results);
$this->assertInstanceOf(\DateTime::class, $results[0]);
$this->assertInstanceOf(\DateTimeImmutable::class, $results[0]);
$this->assertSame($timezone, $results[0]->getTimezone()->getName(), 'Default timezone');
$this->assertEquals('2012-07-21 00:00:00', $results[0]->format('Y-m-d H:i:s'));
}
Expand All @@ -95,13 +95,13 @@ public function testUnixTimestamp(string $timezone)
date_default_timezone_set($timezone);
$resolver = new DateTimeValueResolver();

$argument = new ArgumentMetadata('dummy', \DateTime::class, false, false, null);
$argument = new ArgumentMetadata('dummy', \DateTimeImmutable::class, false, false, null);
$request = self::requestWithAttributes(['dummy' => '989541720']);

$results = $resolver->resolve($request, $argument);

$this->assertCount(1, $results);
$this->assertInstanceOf(\DateTime::class, $results[0]);
$this->assertInstanceOf(\DateTimeImmutable::class, $results[0]);
$this->assertSame('+00:00', $results[0]->getTimezone()->getName(), 'Timestamps are UTC');
$this->assertEquals('2001-05-11 00:42:00', $results[0]->format('Y-m-d H:i:s'));
}
Expand All @@ -110,7 +110,7 @@ public function testNullableWithEmptyAttribute()
{
$resolver = new DateTimeValueResolver();

$argument = new ArgumentMetadata('dummy', \DateTime::class, false, false, null, true);
$argument = new ArgumentMetadata('dummy', \DateTimeImmutable::class, false, false, null, true);
$request = self::requestWithAttributes(['dummy' => '']);

$results = $resolver->resolve($request, $argument);
Expand All @@ -123,8 +123,8 @@ public function testPreviouslyConvertedAttribute()
{
$resolver = new DateTimeValueResolver();

$argument = new ArgumentMetadata('dummy', \DateTime::class, false, false, null, true);
$request = self::requestWithAttributes(['dummy' => $datetime = new \DateTime()]);
$argument = new ArgumentMetadata('dummy', \DateTimeImmutable::class, false, false, null, true);
$request = self::requestWithAttributes(['dummy' => $datetime = new \DateTimeImmutable()]);

$results = $resolver->resolve($request, $argument);

Expand Down Expand Up @@ -191,15 +191,15 @@ public function provideInvalidDates()
{
return [
'invalid date' => [
new ArgumentMetadata('dummy', \DateTime::class, false, false, null),
new ArgumentMetadata('dummy', \DateTimeImmutable::class, false, false, null),
self::requestWithAttributes(['dummy' => 'Invalid DateTime Format']),
],
'invalid format' => [
new ArgumentMetadata('dummy', \DateTime::class, false, false, null, false, [new MapDateTime(format: 'd.m.Y')]),
new ArgumentMetadata('dummy', \DateTimeImmutable::class, false, false, null, false, [new MapDateTime(format: 'd.m.Y')]),
self::requestWithAttributes(['dummy' => '2012-07-21']),
],
'invalid ymd format' => [
new ArgumentMetadata('dummy', \DateTime::class, false, false, null, false, [new MapDateTime(format: 'Y-m-d')]),
new ArgumentMetadata('dummy', \DateTimeImmutable::class, false, false, null, false, [new MapDateTime(format: 'Y-m-d')]),
self::requestWithAttributes(['dummy' => '2012-21-07']),
],
];
Expand Down Expand Up @@ -230,6 +230,6 @@ private static function requestWithAttributes(array $attributes): Request
}
}

class FooDateTime extends \DateTime
class FooDateTime extends \DateTimeImmutable
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ public function testCollect()
$this->assertSame(sprintf('%s.%s', Kernel::MAJOR_VERSION, Kernel::MINOR_VERSION), $c->getSymfonyMinorVersion());
$this->assertContains($c->getSymfonyState(), ['eol', 'eom', 'dev', 'stable']);

$eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->format('F Y');
$eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->format('F Y');
$eom = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->format('F Y');
$eol = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->format('F Y');
$this->assertSame($eom, $c->getSymfonyEom());
$this->assertSame($eol, $c->getSymfonyEol());
}
Expand All @@ -72,8 +72,8 @@ public function testCollectWithoutKernel()
$this->assertSame(sprintf('%s.%s', Kernel::MAJOR_VERSION, Kernel::MINOR_VERSION), $c->getSymfonyMinorVersion());
$this->assertContains($c->getSymfonyState(), ['eol', 'eom', 'dev', 'stable']);

$eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->format('F Y');
$eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->format('F Y');
$eom = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->format('F Y');
$eol = \DateTimeImmutable::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->format('F Y');
$this->assertSame($eom, $c->getSymfonyEom());
$this->assertSame($eol, $c->getSymfonyEol());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ protected function createResponse()
$response->headers->set('Content-Type', 'application/json');
$response->headers->set('X-Foo-Bar', null);
$response->headers->setCookie(new Cookie('foo', 'bar', 1, '/foo', 'localhost', true, true, false, null));
$response->headers->setCookie(new Cookie('bar', 'foo', new \DateTime('@946684800'), '/', null, false, true, false, null));
$response->headers->setCookie(new Cookie('bar', 'foo', new \DateTimeImmutable('@946684800'), '/', null, false, true, false, null));
$response->headers->setCookie(new Cookie('bazz', 'foo', '2000-12-12', '/', null, false, true, false, null));

return $response;
Expand Down
Loading