Use DatetimeImmutable instead of DateTime wherever possible

This commit is contained in:
Jan Böhmer 2024-06-22 17:36:54 +02:00
parent eebc373734
commit 235d572f8c
39 changed files with 222 additions and 112 deletions

View file

@ -225,7 +225,7 @@ trait PKImportHelperTrait
protected function setCreationDate(TimeStampableInterface $entity, ?string $datetime_str): void
{
if ($datetime_str !== null && $datetime_str !== '' && $datetime_str !== '0000-00-00 00:00:00') {
$date = new \DateTime($datetime_str);
$date = new \DateTimeImmutable($datetime_str);
} else {
$date = null; //Null means "now" at persist time
}

View file

@ -97,7 +97,7 @@ final class LabelExampleElementsGenerator
$lot->setDescription('Example Lot');
$lot->setComment('Lot comment');
$lot->setExpirationDate(new DateTime('+1 days'));
$lot->setExpirationDate(new \DateTimeImmutable('+1 day'));
$lot->setStorageLocation($this->getStructuralData(StorageLocation::class));
$lot->setAmount(123);
$lot->setOwner($this->getUser());

View file

@ -81,7 +81,7 @@ final class GlobalProviders implements PlaceholderProviderInterface
return 'anonymous';
}
$now = new DateTime();
$now = new \DateTimeImmutable();
if ('[[DATETIME]]' === $placeholder) {
$formatter = IntlDateFormatter::create(

View file

@ -42,7 +42,6 @@ declare(strict_types=1);
namespace App\Services\LabelSystem\PlaceholderProviders;
use App\Entity\Contracts\TimeStampableInterface;
use DateTime;
use IntlDateFormatter;
use Locale;
@ -57,11 +56,11 @@ final class TimestampableElementProvider implements PlaceholderProviderInterface
$formatter = new IntlDateFormatter(Locale::getDefault(), IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
if ('[[LAST_MODIFIED]]' === $placeholder) {
return $formatter->format($label_target->getLastModified() ?? new DateTime());
return $formatter->format($label_target->getLastModified() ?? new \DateTimeImmutable());
}
if ('[[CREATION_DATE]]' === $placeholder) {
return $formatter->format($label_target->getAddedDate() ?? new DateTime());
return $formatter->format($label_target->getAddedDate() ?? new \DateTimeImmutable());
}
}

View file

@ -136,7 +136,7 @@ class LogDataFormatter
}
try {
$dateTime = new \DateTime($date, new \DateTimeZone($timezone));
$dateTime = new \DateTimeImmutable($date, new \DateTimeZone($timezone));
} catch (\Exception) {
return '<i>unknown DateTime format</i>';
}

View file

@ -34,11 +34,13 @@ use App\Repository\LogEntryRepository;
use Brick\Math\BigDecimal;
use DateTime;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\MappingException;
use Exception;
use InvalidArgumentException;
use PHPUnit\Util\Type;
use ReflectionClass;
class TimeTravel
@ -171,17 +173,26 @@ class TimeTravel
/**
* This function decodes the array which is created during the json_encode of a datetime object and returns a DateTime object.
* @param array $input
* @return DateTime
* @return \DateTimeInterface
* @throws Exception
*/
private function dateTimeDecode(?array $input): ?\DateTime
private function dateTimeDecode(?array $input, string $doctrineType): ?\DateTimeInterface
{
//Allow null values
if ($input === null) {
return null;
}
return new \DateTime($input['date'], new \DateTimeZone($input['timezone']));
//Mutable types
if (in_array($doctrineType, [Types::DATETIME_MUTABLE, Types::DATE_MUTABLE], true)) {
return new \DateTime($input['date'], new \DateTimeZone($input['timezone']));
}
//Immutable types
if (in_array($doctrineType, [Types::DATETIME_IMMUTABLE, Types::DATE_IMMUTABLE], true)) {
return new \DateTimeImmutable($input['date'], new \DateTimeZone($input['timezone']));
}
throw new InvalidArgumentException('The given doctrine type is not a datetime type!');
}
/**
@ -208,8 +219,10 @@ class TimeTravel
$data = BigDecimal::of($data);
}
if (!$data instanceof DateTime && ('datetime' === $metadata->getFieldMapping($field)['type'])) {
$data = $this->dateTimeDecode($data);
if (!$data instanceof \DateTimeInterface
&& (in_array($metadata->getFieldMapping($field)['type'],
[Types::DATETIME_IMMUTABLE, Types::DATETIME_IMMUTABLE, Types::DATE_MUTABLE, Types::DATETIME_IMMUTABLE], true))) {
$data = $this->dateTimeDecode($data, $metadata->getFieldMapping($field)['type']);
}
$this->setField($element, $field, $data);

View file

@ -49,7 +49,7 @@ final class SidebarTreeUpdater
//This tag and therfore this whole cache gets cleared by TreeCacheInvalidationListener when a structural element is changed
$item->tag('sidebar_tree_update');
return new \DateTime();
return new \DateTimeImmutable();
});
}
}

View file

@ -59,8 +59,7 @@ class PasswordResetManager
$user->setPwResetToken($this->passwordEncoder->hash($unencrypted_token));
//Determine the expiration datetime of
$expiration_date = new DateTime();
$expiration_date->add(date_interval_create_from_date_string('1 day'));
$expiration_date = new \DateTimeImmutable("+1 day");
$user->setPwResetExpires($expiration_date);
if ($user->getEmail() !== null && $user->getEmail() !== '') {
@ -105,7 +104,7 @@ class PasswordResetManager
}
//Check if token is expired yet
if ($user->getPwResetExpires() < new DateTime()) {
if ($user->getPwResetExpires() < new \DateTimeImmutable()) {
return false;
}
@ -119,7 +118,7 @@ class PasswordResetManager
//Remove token
$user->setPwResetToken(null);
$user->setPwResetExpires(new DateTime());
$user->setPwResetExpires(new \DateTimeImmutable());
//Save to DB
$this->em->flush();