Skip to content

Commit

Permalink
Use DatetimeImmutable instead of DateTime wherever possible
Browse files Browse the repository at this point in the history
  • Loading branch information
jbtronics committed Jun 22, 2024
1 parent eebc373 commit 235d572
Show file tree
Hide file tree
Showing 39 changed files with 222 additions and 112 deletions.
7 changes: 7 additions & 0 deletions config/packages/doctrine.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,17 @@ doctrine:
# either here or in the DATABASE_URL env var (see .env file)

types:
# UTC datetimes
datetime:
class: App\Doctrine\Types\UTCDateTimeType
date:
class: App\Doctrine\Types\UTCDateTimeType

datetime_immutable:
class: App\Doctrine\Types\UTCDateTimeImmutableType
date_immutable:
class: App\Doctrine\Types\UTCDateTimeImmutableType

big_decimal:
class: App\Doctrine\Types\BigDecimalType
tinyint:
Expand Down
2 changes: 1 addition & 1 deletion src/DataFixtures/APITokenFixtures.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function load(ObjectManager $manager): void
$expired_token->setUser($admin_user);
$expired_token->setLevel(ApiTokenLevel::FULL);
$expired_token->setName('expired');
$expired_token->setValidUntil(new \DateTime('-1 day'));
$expired_token->setValidUntil(new \DateTimeImmutable('-1 day'));
$this->setTokenSecret($expired_token, self::TOKEN_EXPIRED);
$manager->persist($expired_token);

Expand Down
2 changes: 1 addition & 1 deletion src/DataFixtures/PartFixtures.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public function load(ObjectManager $manager): void
$part->addPartLot($partLot1);

$partLot2 = new PartLot();
$partLot2->setExpirationDate(new DateTime());
$partLot2->setExpirationDate(new \DateTimeImmutable());
$partLot2->setComment('Test');
$partLot2->setNeedsRefill(true);
$partLot2->setStorageLocation($manager->find(StorageLocation::class, 3));
Expand Down
2 changes: 1 addition & 1 deletion src/DataTables/Column/LocaleDateTimeColumn.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function normalize($value): string
}

if (!$value instanceof DateTimeInterface) {
$value = new DateTime((string) $value);
$value = new \DateTimeImmutable((string) $value);
}

$formatValues = [
Expand Down
97 changes: 97 additions & 0 deletions src/Doctrine/Types/UTCDateTimeImmutableType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
* Copyright (C) 2019 - 2022 Jan Böhmer (https://github.com/jbtronics)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

declare(strict_types=1);

namespace App\Doctrine\Types;

use DateTime;
use DateTimeInterface;
use DateTimeZone;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeImmutableType;
use Doctrine\DBAL\Types\DateTimeType;
use Doctrine\DBAL\Types\Exception\InvalidFormat;

/**
* This DateTimeImmutableType all dates to UTC, so it can be later used with the timezones.
* Taken (and adapted) from here: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/cookbook/working-with-datetime.html.
*/
class UTCDateTimeImmutableType extends DateTimeImmutableType
{
private static ?DateTimeZone $utc_timezone = null;

/**
* {@inheritdoc}
*
* @param T $value
*
* @return (T is null ? null : string)
*
* @template T
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
{
if (!self::$utc_timezone instanceof \DateTimeZone) {
self::$utc_timezone = new DateTimeZone('UTC');
}

if ($value instanceof \DateTimeImmutable) {
$value = $value->setTimezone(self::$utc_timezone);
}

return parent::convertToDatabaseValue($value, $platform);
}

/**
* {@inheritDoc}
*
* @param T $value
*
* @template T
*/
public function convertToPHPValue($value, AbstractPlatform $platform): ?\DateTimeImmutable
{
if (!self::$utc_timezone instanceof \DateTimeZone) {
self::$utc_timezone = new DateTimeZone('UTC');
}

if (null === $value || $value instanceof \DateTimeImmutable) {
return $value;
}

$converted = \DateTimeImmutable::createFromFormat(
$platform->getDateTimeFormatString(),
$value,
self::$utc_timezone
);

if (!$converted) {
throw InvalidFormat::new(
$value,
static::class,
$platform->getDateTimeFormatString(),
);
}

return $converted;
}
}
4 changes: 2 additions & 2 deletions src/Entity/Attachments/Attachment.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,9 @@ abstract class Attachment extends AbstractNamedDBElement
protected ?AttachmentType $attachment_type = null;

#[Groups(['attachment:read'])]
protected ?\DateTime $addedDate = null;
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['attachment:read'])]
protected ?\DateTime $lastModified = null;
protected ?\DateTimeImmutable $lastModified = null;


public function __construct()
Expand Down
4 changes: 2 additions & 2 deletions src/Entity/Attachments/AttachmentType.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,9 @@ class AttachmentType extends AbstractStructuralDBElement
protected Collection $attachments_with_type;

#[Groups(['attachment_type:read'])]
protected ?\DateTime $addedDate = null;
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['attachment_type:read'])]
protected ?\DateTime $lastModified = null;
protected ?\DateTimeImmutable $lastModified = null;


public function __construct()
Expand Down
4 changes: 2 additions & 2 deletions src/Entity/Base/AbstractCompany.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@
abstract class AbstractCompany extends AbstractPartsContainingDBElement
{
#[Groups(['company:read'])]
protected ?\DateTime $addedDate = null;
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['company:read'])]
protected ?\DateTime $lastModified = null;
protected ?\DateTimeImmutable $lastModified = null;

/**
* @var string The address of the company
Expand Down
24 changes: 12 additions & 12 deletions src/Entity/Base/TimestampTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,28 +34,28 @@
trait TimestampTrait
{
/**
* @var \DateTime|null the date when this element was modified the last time
* @var \DateTimeImmutable|null the date when this element was modified the last time
*/
#[Groups(['extended', 'full'])]
#[ApiProperty(writable: false)]
#[ORM\Column(name: 'last_modified', type: Types::DATETIME_MUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
protected ?\DateTime $lastModified = null;
#[ORM\Column(name: 'last_modified', type: Types::DATETIME_IMMUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
protected ?\DateTimeImmutable $lastModified = null;

/**
* @var \DateTime|null the date when this element was created
* @var \DateTimeImmutable|null the date when this element was created
*/
#[Groups(['extended', 'full'])]
#[ApiProperty(writable: false)]
#[ORM\Column(name: 'datetime_added', type: Types::DATETIME_MUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
protected ?\DateTime $addedDate = null;
#[ORM\Column(name: 'datetime_added', type: Types::DATETIME_IMMUTABLE, options: ['default' => 'CURRENT_TIMESTAMP'])]
protected ?\DateTimeImmutable $addedDate = null;

/**
* Returns the last time when the element was modified.
* Returns null if the element was not yet saved to DB yet.
*
* @return \DateTimeInterface|null the time of the last edit
* @return \DateTimeImmutable|null the time of the last edit
*/
public function getLastModified(): ?\DateTimeInterface
public function getLastModified(): ?\DateTimeImmutable
{
return $this->lastModified;
}
Expand All @@ -64,9 +64,9 @@ public function getLastModified(): ?\DateTimeInterface
* Returns the date/time when the element was created.
* Returns null if the element was not yet saved to DB yet.
*
* @return \DateTimeInterface|null the creation time of the part
* @return \DateTimeImmutable|null the creation time of the part
*/
public function getAddedDate(): ?\DateTimeInterface
public function getAddedDate(): ?\DateTimeImmutable
{
return $this->addedDate;
}
Expand All @@ -78,9 +78,9 @@ public function getAddedDate(): ?\DateTimeInterface
#[ORM\PreUpdate]
public function updateTimestamps(): void
{
$this->lastModified = new DateTime('now');
$this->lastModified = new \DateTimeImmutable('now');
if (null === $this->addedDate) {
$this->addedDate = new DateTime('now');
$this->addedDate = new \DateTimeImmutable('now');
}
}
}
14 changes: 7 additions & 7 deletions src/Entity/LogSystem/AbstractLogEntry.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
use Doctrine\DBAL\Types\Types;
use App\Entity\Base\AbstractDBElement;
use App\Entity\UserSystem\User;
use DateTime;

use Doctrine\ORM\Mapping as ORM;
use App\Repository\LogEntryRepository;

Expand Down Expand Up @@ -56,10 +56,10 @@ abstract class AbstractLogEntry extends AbstractDBElement
protected string $username = '';

/**
* @var \DateTimeInterface The datetime the event associated with this log entry has occured
* @var \DateTimeImmutable The datetime the event associated with this log entry has occured
*/
#[ORM\Column(name: 'datetime', type: Types::DATETIME_MUTABLE)]
protected \DateTimeInterface $timestamp;
#[ORM\Column(name: 'datetime', type: Types::DATETIME_IMMUTABLE)]
protected \DateTimeImmutable $timestamp;

/**
* @var LogLevel The priority level of the associated level. 0 is highest, 7 lowest
Expand Down Expand Up @@ -90,7 +90,7 @@ abstract class AbstractLogEntry extends AbstractDBElement

public function __construct()
{
$this->timestamp = new DateTime();
$this->timestamp = new \DateTimeImmutable();
}

/**
Expand Down Expand Up @@ -165,7 +165,7 @@ public function getUsername(): string
/**
* Returns the timestamp when the event that caused this log entry happened.
*/
public function getTimestamp(): \DateTimeInterface
public function getTimestamp(): \DateTimeImmutable
{
return $this->timestamp;
}
Expand All @@ -175,7 +175,7 @@ public function getTimestamp(): \DateTimeInterface
*
* @return $this
*/
public function setTimestamp(\DateTime $timestamp): self
public function setTimestamp(\DateTimeImmutable $timestamp): self
{
$this->timestamp = $timestamp;

Expand Down
2 changes: 1 addition & 1 deletion src/Entity/OAuthToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public function getToken(): ?string
return $this->token;
}

public function getExpirationDate(): ?\DateTimeInterface
public function getExpirationDate(): ?\DateTimeImmutable
{
return $this->expires_at;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Entity/Parts/Category.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,9 @@ class Category extends AbstractPartsContainingDBElement
protected Collection $parameters;

#[Groups(['category:read'])]
protected ?\DateTime $addedDate = null;
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['category:read'])]
protected ?\DateTime $lastModified = null;
protected ?\DateTimeImmutable $lastModified = null;

#[Assert\Valid]
#[ORM\Embedded(class: EDACategoryInfo::class)]
Expand Down
4 changes: 2 additions & 2 deletions src/Entity/Parts/Footprint.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,9 @@ class Footprint extends AbstractPartsContainingDBElement
protected Collection $parameters;

#[Groups(['footprint:read'])]
protected ?\DateTime $addedDate = null;
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['footprint:read'])]
protected ?\DateTime $lastModified = null;
protected ?\DateTimeImmutable $lastModified = null;

#[Assert\Valid]
#[ORM\Embedded(class: EDAFootprintInfo::class)]
Expand Down
11 changes: 5 additions & 6 deletions src/Entity/Parts/InfoProviderReference.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ class InfoProviderReference
#[Groups(['provider_reference:read'])]
private ?string $provider_url = null;

#[Column(type: Types::DATETIME_MUTABLE, nullable: true, options: ['default' => null])]
#[Column(type: Types::DATETIME_IMMUTABLE, nullable: true, options: ['default' => null])]
#[Groups(['provider_reference:read'])]
private ?\DateTime $last_updated = null;
private ?\DateTimeImmutable $last_updated = null;

/**
* Constructing is forbidden from outside.
Expand Down Expand Up @@ -95,9 +95,8 @@ public function getProviderUrl(): ?string

/**
* Gets the time, when the part was last time updated by the provider.
* @return \DateTimeInterface|null
*/
public function getLastUpdated(): ?\DateTimeInterface
public function getLastUpdated(): ?\DateTimeImmutable
{
return $this->last_updated;
}
Expand Down Expand Up @@ -140,7 +139,7 @@ public static function providerReference(string $provider_key, string $provider_
$ref->provider_key = $provider_key;
$ref->provider_id = $provider_id;
$ref->provider_url = $provider_url;
$ref->last_updated = new \DateTime();
$ref->last_updated = new \DateTimeImmutable();
return $ref;
}

Expand All @@ -155,7 +154,7 @@ public static function fromPartDTO(SearchResultDTO $dto): self
$ref->provider_key = $dto->provider_key;
$ref->provider_id = $dto->provider_id;
$ref->provider_url = $dto->provider_url;
$ref->last_updated = new \DateTime();
$ref->last_updated = new \DateTimeImmutable();
return $ref;
}
}
4 changes: 2 additions & 2 deletions src/Entity/Parts/MeasurementUnit.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ class MeasurementUnit extends AbstractPartsContainingDBElement
protected Collection $parameters;

#[Groups(['measurement_unit:read'])]
protected ?\DateTime $addedDate = null;
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['measurement_unit:read'])]
protected ?\DateTime $lastModified = null;
protected ?\DateTimeImmutable $lastModified = null;


/**
Expand Down
4 changes: 2 additions & 2 deletions src/Entity/Parts/Part.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,9 @@ class Part extends AttachmentContainingDBElement
protected ?Attachment $master_picture_attachment = null;

#[Groups(['part:read'])]
protected ?\DateTime $addedDate = null;
protected ?\DateTimeImmutable $addedDate = null;
#[Groups(['part:read'])]
protected ?\DateTime $lastModified = null;
protected ?\DateTimeImmutable $lastModified = null;


public function __construct()
Expand Down
Loading

0 comments on commit 235d572

Please sign in to comment.