44
55namespace SimpleSAML \XMLSchema \Type ;
66
7+ use DateTimeImmutable ;
8+ use DateTimeInterface ;
9+ use Psr \Clock \ClockInterface ;
710use SimpleSAML \XML \Assert \Assert ;
811use SimpleSAML \XMLSchema \Exception \SchemaViolationException ;
912use SimpleSAML \XMLSchema \Type \Interface \AbstractAnySimpleType ;
1013
11- use function rtrim ;
12- use function strlen ;
13- use function substr ;
14+ use function preg_replace ;
1415
1516/**
1617 * @package simplesaml/xml-common
@@ -19,6 +20,7 @@ class TimeValue extends AbstractAnySimpleType
1920{
2021 public const string SCHEMA_TYPE = 'time ' ;
2122
23+ public const string DATETIME_FORMAT = 'H:i:s.uP ' ;
2224
2325 /**
2426 * Sanitize the value.
@@ -29,26 +31,10 @@ protected function sanitizeValue(string $value): string
2931 {
3032 $ normalized = static ::collapseWhitespace (static ::normalizeWhitespace ($ value ));
3133
32- // Trim any trailing zero's from the sub-seconds
33- $ decimal = strrpos ($ normalized , '. ' );
34- if ($ decimal !== false ) {
35- $ timezone = strrpos ($ normalized , '+ ' ) ?: strrpos ($ normalized , '- ' ) ?: strrpos ($ normalized , 'Z ' );
36- if ($ timezone !== false ) {
37- $ subseconds = substr ($ normalized , $ decimal + $ timezone , strlen ($ normalized ) - $ timezone );
38- } else {
39- $ subseconds = substr ($ normalized , $ decimal + 1 );
40- }
41-
42- $ subseconds = rtrim ($ subseconds , '0 ' );
43- if ($ subseconds === '' ) {
44- return substr ($ normalized , 0 , $ decimal );
45- }
46- return substr ($ normalized , 0 , $ decimal + 1 )
47- . $ subseconds
48- . (($ timezone === false ) ? '' : substr ($ normalized , $ timezone ));
49- }
50-
51- return $ normalized ;
34+ $ sanitized = preg_replace ('/\.0+/ ' , '' , $ normalized );
35+ $ sanitized = preg_replace ('/\.(?!\d)/ ' , '' , $ sanitized );
36+
37+ return $ sanitized ;
5238 }
5339
5440
@@ -62,4 +48,29 @@ protected function validateValue(string $value): void
6248 {
6349 Assert::validTime ($ this ->sanitizeValue ($ value ), SchemaViolationException::class);
6450 }
51+
52+
53+ /**
54+ */
55+ public static function now (ClockInterface $ clock ): static
56+ {
57+ return static ::fromDateTime ($ clock ->now ());
58+ }
59+
60+
61+ /**
62+ * @param \DateTimeInterface $value
63+ */
64+ public static function fromDateTime (DateTimeInterface $ value ): static
65+ {
66+ return new static ($ value ->format (static ::DATETIME_FORMAT ));
67+ }
68+
69+
70+ /**
71+ */
72+ public function toDateTime (): DateTimeImmutable
73+ {
74+ return new DateTimeImmutable ($ this ->getValue ());
75+ }
6576}
0 commit comments