Passed
Pull Request — master (#61)
by Tim
02:17
created

DateTimeValue   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 50
rs 10
c 0
b 0
f 0
wmc 4

4 Methods

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