8000 Remove unnecessary usages of DateTime by nicolas-grekas · Pull Request #50297 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

Remove unnecessary usages of DateTime #50297

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
Jun 3, 2023
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
29 changes: 18 additions & 11 deletions .github/expected-missing-return-types.diff
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ index 38618fc15e..eb599eb0b4 100644
{
$this->clearEntityManagers();
diff --git a/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php b/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php
index 9d61be61bd..e89985de26 100644
index 3af51ffd60..2743b97f31 100644
--- a/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php
+++ b/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php
@@ -70,5 +70,5 @@ class DoctrineTokenProvider implements TokenProviderInterface, TokenVerifierInte
Expand Down Expand Up @@ -6182,7 +6182,7 @@ index 32c58447cd..ec35f6ee41 100644
{
$compound = static fn (Options $options) => 'single_text' !== $options['widget'];
diff --git a/src/Symfony/Component/Form/Extension/Core/Type/DateType.php b/src/Symfony/Component/Form/Extension/Core/Type/DateType.php
index 3b68dc241a..474139a6ee 100644
index 80023affcb..d6051f52d1 100644
--- a/src/Symfony/Component/Form/Extension/Core/Type/DateType.php
+++ b/src/Symfony/Component/Form/Extension/Core/Type/DateType.php
@@ -47,5 +47,5 @@ class DateType extends AbstractType
Expand Down Expand Up @@ -7352,7 +7352,7 @@ index a87171d2ca..cec8a6f027 100644
{
if ($this->client instanceof ResetInterface) {
diff --git a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
index cd716e590e..68a0479ef4 100644
index 71e806fc15..d60290b3ed 100644
--- a/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
+++ b/src/Symfony/Component/HttpFoundation/BinaryFileResponse.php
@@ -362,5 +362,5 @@ class BinaryFileResponse extends Response
Expand Down Expand Up @@ -7399,7 +7399,7 @@ index b74a02e2e1..51b4f7f1c3 100644
{
foreach ($files as $key => $file) {
diff --git a/src/Symfony/Component/HttpFoundation/HeaderBag.php b/src/Symfony/Component/HttpFoundation/HeaderBag.php
index c49a239726..440f3297de 100644
index 3128a1d833..6721bbe974 100644
--- a/src/Symfony/Component/HttpFoundation/HeaderBag.php
+++ b/src/Symfony/Component/HttpFoundation/HeaderBag.php
@@ -90,5 +90,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
Expand Down Expand Up @@ -7430,21 +7430,28 @@ index c49a239726..440f3297de 100644
+ public function remove(string $key): void
{
$key = strtr($key, self::UPPER, self::LOWER);
@@ -214,5 +214,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
@@ -198,5 +198,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
* @throws \RuntimeException When the HTTP header is not parseable
*/
- public function getDate(string $key, \DateTimeInterface $default = null): ?\DateTimeInterface
+ public function getDate(string $key, \DateTimeInterface $default = null): ?\DateTimeImmutable
{
if (null === $value = $this->get($key)) {
@@ -216,5 +216,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
* @return void
*/
- public function addCacheControlDirective(string $key, bool|string $value = true)
+ public function addCacheControlDirective(string $key, bool|string $value = true): void
{
$this->cacheControl[$key] = $value;
@@ -242,5 +242,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
@@ -244,5 +244,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
* @return void
*/
- public function removeCacheControlDirective(string $key)
+ public function removeCacheControlDirective(string $key): void
{
unset($this->cacheControl[$key]);
@@ -270,5 +270,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
@@ -272,5 +272,5 @@ class HeaderBag implements \IteratorAggregate, \Countable
* @return string
*/
- protected function getCacheControlHeader()
Expand Down Expand Up @@ -12907,7 +12914,7 @@ index d53bbb196f..4eecf85f8e 100644
{
return self::PROPERTY_CONSTRAINT;
diff --git a/src/Symfony/Component/Validator/ConstraintValidator.php b/src/Symfony/Component/Validator/ConstraintValidator.php
index 8fa522314f..a4c0c5ec64 100644
index 3c4167be33..59e5b3c09e 100644
--- a/src/Symfony/Component/Validator/ConstraintValidator.php
+++ b/src/Symfony/Component/Validator/ConstraintValidator.php
@@ -40,5 +40,5 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
Expand Down Expand Up @@ -12998,7 +13005,7 @@ index 1fdbf0bc3f..aad702453b 100644
+ public function remove(int $offset): void;
}
diff --git a/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php b/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php
index 29fd4daa8a..c358e6cc6f 100644
index a81d589f2b..87155e513c 100644
--- a/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php
+++ b/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php
@@ -38,5 +38,5 @@ abstract class AbstractComparisonValidator extends ConstraintValidator
Expand Down Expand Up @@ -13170,7 +13177,7 @@ index a50ea62ab6..5f5b5b4e5a 100644
{
if (!$constraint instanceof Currency) {
diff --git a/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php b/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php
index f02ba54daf..e89c616ec8 100644
index c88732d4d8..4c0e11eacf 100644
--- a/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php
+++ b/src/Symfony/Component/Validator/Constraints/DateTimeValidator.php
@@ -25,5 +25,5 @@ class DateTimeValidator extends DateValidator
Expand Down Expand Up @@ -13455,7 +13462,7 @@ index 3f8f951280..503e779244 100644
{
if (!$constraint instanceof NotNull) {
diff --git a/src/Symfony/Component/Validator/Constraints/RangeValidator.php b/src/Symfony/Component/Validator/Constraints/RangeValidator.php
index 18c399cd08..c98312a9aa 100644
index 73273d6788..f8d0945f23 100644
--- a/src/Symfony/Component/Validator/Constraints/RangeValidator.php
+++ b/src/Symfony/Component/Validator/Constraints/RangeValidator.php
@@ -35,5 +35,5 @@ class RangeValidator extends ConstraintValidator
Expand Down
7 changes: 7 additions & 0 deletions UPGRADE-6.4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
UPGRADE FROM 6.3 to 6.4
=======================

HttpFoundation
--------------

* Make `HeaderBag::getDate()`, `Response::getDate()`, `getExpires()` and `getLastModified()` return a `DateTimeImmutable`
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ public function updateToken(string $series, #[\SensitiveParameter] string $token
$sql = 'UPDATE rememberme_token SET value=:value, lastUsed=:lastUsed WHERE series=:series';
$paramValues = [
'value' => $tokenValue,
'lastUsed' => $lastUsed,
'lastUsed' => \DateTimeImmutable::createFromInterface($lastUsed),
'series' => $series,
];
$paramTypes = [
'value' => ParameterType::STRING,
'lastUsed' => Types::DATETIME_MUTABLE,
'lastUsed' => Types::DATETIME_IMMUTABLE,
'series' => ParameterType::STRING,
];
if (method_exists($this->conn, 'executeStatement')) {
Expand All @@ -118,14 +118,14 @@ public function createNewToken(PersistentTokenInterface $token)
'username' => $token->getUserIdentifier(),
'series' => $token->getSeries(),
'value' => $token->getTokenValue(),
'lastUsed' => $token->getLastUsed(),
'lastUsed' => \DateTimeImmutable::createFromInterface($token->getLastUsed()),
];
$paramTypes = [
'class' => ParameterType::STRING,
'username' => ParameterType::STRING,
'series' => ParameterType::STRING,
'value' => ParameterType::STRING,
'lastUsed' => Types::DATETIME_MUTABLE,
'lastUsed' => Types::DATETIME_IMMUTABLE,
];
if (method_exists($this->conn, 'executeStatement')) {
$this->conn->executeStatement($sql, $paramValues, $paramTypes);
Expand Down Expand Up @@ -186,6 +186,7 @@ public function updateExistingToken(PersistentTokenInterface $token, #[\Sensitiv
$this->conn->beginTransaction();
try {
$this->deleteTokenBySeries($tmpSeries);
$lastUsed = \DateTime::createFromInterface($lastUsed);
$this->createNewToken(new PersistentToken($token->getClass(), $token->getUserIdentifier(), $tmpSeries, $token->getTokenValue(), $lastUsed));

$this->conn->commit();
Expand Down Expand Up @@ -220,7 +221,7 @@ private function addTableToSchema(Schema $schema): void
$table = $schema->createTable('rememberme_token');
$table->addColumn('series', Types::STRING, ['length' => 88]);
$table->addColumn('value', Types::STRING, ['length' => 88]);
$table->addColumn('lastUsed', Types::DATETIME_MUTABLE);
$table->addColumn('lastUsed', Types::DATETIME_IMMUTABLE);
$table->addColumn('class', Types::STRING, ['length' => 100]);
$table->addColumn('username', Types::STRING, ['length' => 200]);
$table->setPrimaryKey(['series']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public static function paramProvider(): array
[true, [], true, true],
[null, [], null, true],
[new \DateTime('2011-09-11'), ['date'], '2011-09-11', true],
[new \DateTimeImmutable('2011-09-11'), ['date_immutable'], '2011-09-11', true],
[fopen(__FILE__, 'r'), [], '/* Resource(stream) */', false, false],
[
new \stdClass(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public function testWithValueBound(callable $executeMethod)
$stmt->bindValue(3, 5, ParameterType::INTEGER);
$stmt->bindValue(4, $res = $this->getResourceFromString('mydata'), ParameterType::BINARY);
$stmt->bindValue(5, ['foo', 'bar'], Types::SIMPLE_ARRAY);
$stmt->bindValue(6, new \DateTime('2022-06-12 11:00:00'), Types::DATETIME_MUTABLE);
$stmt->bindValue(6, new \DateTimeImmutable('2022-06-12 11:00:00'), Types::DATETIME_IMMUTABLE);

$executeMethod($stmt);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function testVerifyOutdatedTokenAfterParallelRequest()
$provider->createNewToken($token);

// new request comes in requiring remember-me auth, which updates the token
$provider->updateExistingToken($token, $newValue, new \DateTime('-5 seconds'));
$provider->updateExistingToken($token, $newValue, new \DateTimeImmutable('-5 seconds'));
$provider->updateToken($series, $newValue, new \DateTime('-5 seconds'));

// parallel request comes in with the old remember-me cookie and session, which also requires reauth
Expand All @@ -102,7 +102,7 @@ public function testVerifyOutdatedTokenAfterParallelRequestFailsAfter60Seconds()
$provider->createNewToken($token);

// new request comes in requiring remember-me auth, which updates the token
$provider->updateExistingToken($token, $newValue, new \DateTime('-61 seconds'));
$provider->updateExistingToken($token, $newValue, new \DateTimeImmutable('-61 seconds'));
$provider->updateToken($series, $newValue, new \DateTime('-5 seconds'));

// parallel request comes in with the old remember-me cookie and session, which also requires reauth
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
['Version', \PHP_VERSION],
['Architecture', (\PHP_INT_SIZE * 8).' bits'],
['Intl locale', class_exists(\Locale::class, false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a'],
['Timezone', date_default_timezone_get().' (<comment>'.(new \DateTime())->format(\DateTime::W3C).'</>)'],
['Timezone', date_default_timezone_get().' (<comment>'.(new \DateTimeImmutable())->format(\DateTimeInterface::W3C).'</>)'] F438 ,
['OPcache', \extension_loaded('Zend OPcache') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOL) ? 'true' : 'false'],
['APCu', \extension_loaded('apcu') && filter_var(\ini_get('apc.enabled'), \FILTER_VALIDATE_BOOL) ? 'true' : 'false'],
['Xdebug', \extension_loaded('xdebug') ? 'true' : 'false'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@
%}
<tr class="log-status-{{ css_class }}" data-type="{{ log.type }}" data-priority="{{ log.priority }}" data-channel="{{ log.channel }}" style="{{ 'event' == log.channel or 'DEBUG' == log.priorityName ? 'display: none' }}">
<td class="log-timestamp">
<time class="newline" title="{{ log.timestamp|date('r') }}" datetime="{{ log.timestamp|date(constant('\DateTime::RFC3339_EXTENDED')) }}" data-convert-to-user-timezone data-render-as-time data-render-with-millisecond-precision>
<time class="newline" title="{{ log.timestamp|date('r') }}" datetime="{{ log.timestamp|date(constant('DateTimeInterface::RFC3339_EXTENDED')) }}" data-convert-to-user-timezone data-render-as-time data-render-with-millisecond-precision>
{{ log.timestamp|date('H:i:s.v') }}
</time>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ public function transform(mixed $dateTime): array
}

if ($this->inputTimezone !== $this->outputTimezone) {
if (!$dateTime instanceof \DateTimeImmutable) {
$dateTime = clone $dateTime;
}

$dateTime = \DateTimeImmutable::createFromInterface($dateTime);
$dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ public function transform(mixed $dateTime): string
}

if ($this->inputTimezone !== $this->outputTimezone) {
if (!$dateTime instanceof \DateTimeImmutable) {
$dateTime = clone $dateTime;
}

$dateTime = \DateTimeImmutable::createFromInterface($dateTime);
$dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ public function transform(mixed $dateTime): string
}

if ($this->inputTimezone !== $this->outputTimezone) {
if (!$dateTime instanceof \DateTimeImmutable) {
$dateTime = clone $dateTime;
}

$dateTime = \DateTimeImmutable::createFromInterface($dateTime);
$dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,7 @@ public function transform(mixed $dateTime): string
throw new TransformationFailedException('Expected a \DateTimeInterface.');
}

if (!$dateTime instanceof \DateTimeImmutable) {
$dateTime = clone $dateTime;
}

$dateTime = \DateTimeImmutable::createFromInterface($dateTime);
$dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));

return $dateTime->format($this->generateFormat);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ private function listYears(array $years): array
$result = [];

foreach ($years as $year) {
$result[\PHP_INT_SIZE === 4 ? \DateTime::createFromFormat('Y e', $year.' UTC')->format('U') : gmmktime(0, 0, 0, 6, 15, $year)] = $year;
$result[\PHP_INT_SIZE === 4 ? \DateTimeImmutable::createFromFormat('Y e', $year.' UTC')->format('U') : gmmktime(0, 0, 0, 6, 15, $year)] = $year;
}

return $result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,12 @@ public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess
case '\DateTime':
return new TypeGuess(DateType::class, [], Guess::MEDIUM_CONFIDENCE);

case \DateTimeImmutable::class:
case '\DateTimeImmutable':
case \DateTimeInterface::class:
case '\DateTimeInterface':
return new TypeGuess(DateType::class, ['input' => 'datetime_immutable'], Guess::MEDIUM_CONFIDENCE);

case 'string':
return new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ trait DateTimeEqualsTrait
{
public static function assertDateTimeEquals($expected, $actual)
{
if ($expected instanceof \DateTime && $actual instanceof \DateTime) {
if ($expected instanceof \DateTimeInterface && $actual instanceof \DateTimeInterface) {
$expected = $expected->format('c');
$actual = $actual->format('c');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ public static function guessTypeProvider()
[new Type('long'), new TypeGuess(IntegerType::class, [], Guess::MEDIUM_CONFIDENCE)],
[new Type('string'), new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE)],
[new Type(\DateTime::class), new TypeGuess(DateType::class, [], Guess::MEDIUM_CONFIDENCE)],
[new Type(\DateTimeImmutable::class), new TypeGuess(DateType::class, ['input' => 'datetime_immutable'], Guess::MEDIUM_CONFIDENCE)],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing a case for \DateTimeInterface::class?

[new Type('\DateTime'), new TypeGuess(DateType::class, [], Guess::MEDIUM_CONFIDENCE)],
];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public function setChunkSize(int $chunkSize): static
*/
public function setAutoLastModified(): static
{
$this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
$this->setLastModified(\DateTimeImmutable::createFromFormat('U', $this->file->getMTime()));

return $this;
}
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/HttpFoundation/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.4
---

* Make `HeaderBag::getDate()`, `Response::getDate()`, `getExpires()` and `getLastModified()` return a `DateTimeImmutable`

6.3
---

Expand Down
8 changes: 5 additions & 3 deletions src/Symfony/Component/HttpFoundation/HeaderBag.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,15 +193,17 @@ public function remove(string $key)
/**
* Returns the HTTP header value converted to a date.
*
* @return \DateTimeImmutable|null
*
* @throws \RuntimeException When the HTTP header is not parseable
*/
public function getDate(string $key, \DateTime $default = null): ?\DateTimeInterface
public function getDate(string $key, \DateTimeInterface $default = null): ?\DateTimeInterface
{
if (null === $value = $this->get($key)) {
return $default;
return null !== $default ? \DateTimeImmutable::createFromInterface($default) : null;
}

if (false === $date = \DateTime::createFromFormat(\DATE_RFC2822, $value)) {
if (false === $date = \DateTimeImmutable::createFromFormat(\DATE_RFC2822, $value)) {
throw new \RuntimeException(sprintf('The "%s" HTTP header is not parseable (%s).', $key, $value));
}

Expand Down
Loading
0