Passed
Push — master ( 2155a1...64a139 )
by Tim
02:36
created

DateTimeValue::now()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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