Initial Version
This commit is contained in:
89
core/lib/Db/UTCDateTime.php
Normal file
89
core/lib/Db/UTCDateTime.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace KTXC\Db;
|
||||
|
||||
use MongoDB\BSON\UTCDateTime as MongoUTCDateTime;
|
||||
use DateTimeInterface;
|
||||
|
||||
/**
|
||||
* Wrapper for MongoDB\BSON\UTCDateTime
|
||||
* Provides abstraction layer for MongoDB datetime handling
|
||||
*/
|
||||
class UTCDateTime
|
||||
{
|
||||
private MongoUTCDateTime|string $dateTime;
|
||||
|
||||
/**
|
||||
* Create a new UTCDateTime
|
||||
*
|
||||
* @param int|DateTimeInterface|null $milliseconds Milliseconds since epoch, or DateTime object
|
||||
*/
|
||||
public function __construct(int|DateTimeInterface|null $milliseconds = null)
|
||||
{
|
||||
// Check if MongoDB extension is loaded
|
||||
if (class_exists(MongoUTCDateTime::class)) {
|
||||
$this->dateTime = new MongoUTCDateTime($milliseconds);
|
||||
} else {
|
||||
// Fallback for environments without MongoDB extension (testing, linting)
|
||||
$this->dateTime = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format(DATE_ATOM);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the string representation
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
if ($this->dateTime instanceof MongoUTCDateTime) {
|
||||
return $this->dateTime->toDateTime()->format(DATE_ATOM);
|
||||
}
|
||||
return $this->dateTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying MongoDB UTCDateTime or fallback string
|
||||
* Used internally when interacting with MongoDB driver
|
||||
*/
|
||||
public function toBSON(): MongoUTCDateTime|string
|
||||
{
|
||||
return $this->dateTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert to PHP DateTime
|
||||
*/
|
||||
public function toDateTime(): \DateTimeImmutable
|
||||
{
|
||||
if ($this->dateTime instanceof MongoUTCDateTime) {
|
||||
return \DateTimeImmutable::createFromMutable($this->dateTime->toDateTime());
|
||||
}
|
||||
return new \DateTimeImmutable($this->dateTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get milliseconds since epoch
|
||||
*/
|
||||
public function toMilliseconds(): int
|
||||
{
|
||||
if ($this->dateTime instanceof MongoUTCDateTime) {
|
||||
return (int) $this->dateTime;
|
||||
}
|
||||
return (int) ((new \DateTimeImmutable($this->dateTime))->getTimestamp() * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create from DateTime
|
||||
*/
|
||||
public static function fromDateTime(DateTimeInterface $dateTime): self
|
||||
{
|
||||
return new self($dateTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create current timestamp
|
||||
*/
|
||||
public static function now(): self
|
||||
{
|
||||
return new self();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user