Completed
Push — master ( b4a32a...a386bd )
by Tim
18s queued 14s
created

DateTimeValue::fromDateTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML\Type;
6
7
use DateTimeImmutable;
8
use DateTimeInterface;
9
use SimpleSAML\XML\Assert\Assert;
10
use SimpleSAML\XML\Exception\SchemaViolationException;
11
12
/**
13
 * @package simplesaml/xml-common
14
 */
15
class DateTimeValue extends AbstractValueType
16
{
17
    /** @var string */
18
    public const SCHEMA_TYPE = 'dateTime';
19
20
    /** @var string */
21
    public const DATETIME_FORMAT = 'Y-m-d\\TH:i:sP';
22
23
24
    /**
25
     * Sanitize the value.
26
     *
27
     * @param string $value  The unsanitized value
28
     * @return string
29
     */
30
    protected function sanitizeValue(string $value): string
31
    {
32
        return static::collapseWhitespace(static::normalizeWhitespace($value));
33
    }
34
35
36
    /**
37
     * Validate the value.
38
     *
39
     * @param string $value
40
     * @throws \SimpleSAML\XML\Exception\SchemaViolationException on failure
41
     * @return void
42
     */
43
    protected function validateValue(string $value): void
44
    {
45
        Assert::validDateTime($this->sanitizeValue($value), SchemaViolationException::class);
46
    }
47
48
49
    /**
50
     * @param \DateTimeInterface $value
51
     * @return static
52
     */
53
    public static function fromDateTime(DateTimeInterface $value): static
54
    {
55
        return new static($value->format(static::DATETIME_FORMAT));
56
    }
57
58
59
    /**
60
     * @return \DateTimeImmutable
61
     */
62
    public function toDateTime(): DateTimeImmutable
63
    {
64
        return new DateTimeImmutable($this->getValue());
65
    }
66
}
67