Skip to content

Commit

Permalink
Add DateTimeValue::fromDateTime
Browse files Browse the repository at this point in the history
  • Loading branch information
tvdijen committed Jan 20, 2025
1 parent 15b645b commit 74ce7e7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Type/DateTimeValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SimpleSAML\XML\Type;

use DateTimeInterface;
use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Exception\SchemaViolationException;

Expand All @@ -15,6 +16,9 @@
*/
class DateTimeValue extends AbstractValueType
{
public const string DATETIME_FORMAT = 'Y-m-d\\TH:i:sP';


/**
* Sanitize the value.
*
Expand All @@ -38,4 +42,14 @@ protected function validateValue(string $value): void
{
Assert::validDateTime($this->sanitizeValue($value), SchemaViolationException::class);
}


/**
* @param \DateTimeInterface $value
* @return static
*/
public static function fromDateTime(DateTimeInterface $value): static
{
return new static($value->format(static::DATETIME_FORMAT));
}
}
13 changes: 13 additions & 0 deletions tests/Type/DateTimeValueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SimpleSAML\Test\XML\Type;

use DateTimeImmutable;
use PHPUnit\Framework\Attributes\{CoversClass, DataProvider};
use PHPUnit\Framework\TestCase;
use SimpleSAML\XML\Exception\SchemaViolationException;
Expand Down Expand Up @@ -57,4 +58,16 @@ public static function provideDateTime(): array
'wrong format' => [false, '01-10-26T21:32'],
];
}


/**
* Test the fromDateTime function
*/
public function testFromDateTime(): void
{
$dt = new DateTimeImmutable('@946684800');

$dateTimeValue = DateTimeValue::fromDateTime($dt);
$this->assertEquals('2000-01-01T00:00:00+00:00', $dateTimeValue->getValue());
}
}

0 comments on commit 74ce7e7

Please sign in to comment.