Time::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
/*
6
 * Copyright (c) DateTime-Contributors
7
 *
8
 * Licensed under the MIT License. See LICENSE.md file in the project root
9
 * for full license information.
10
 */
11
12
namespace DateTime;
13
14
use DateTimeImmutable;
15
use DateTimeInterface;
16
use DateTimeZone;
17
18
class Time
19
{
20
    private $datetime;
21
22
    public function __construct(string $time)
23
    {
24
        $tempdate = new DateTimeImmutable($time);
25
        $this->datetime = new DateTimeImmutable(
26
            '1970-01-01 ' . $tempdate->format('H:i:s.u'),
27
            new DateTimeZone('UTC')
28
        );
29
    }
30
31
    public function add(TimeInterval $interval) : Time
32
    {
33
        $self = clone($this);
34
        $self->datetime = $this->datetime->add($interval->getDateTimeInterval());
35
36
        return $self;
37
    }
38
39
    public function sub(TimeInterval $interval) : Time
40
    {
41
        $self = clone($this);
42
        $self->datetime = $this->datetime->sub($interval->getDateTimeInterval());
43
44
        return $self;
45
    }
46
47
    public function format(string $format) : string
48
    {
49
        $format = $this->sanitizeFormatString($format);
50
51
        return $this->datetime->format($format);
52
    }
53
54
    public function diff(Time $time) : TimeInterval
55
    {
56
        return TimeInterval::fromDateTimeInterval(
57
            $this->datetime->diff($time->datetime)
58
        );
59
    }
60
61
    public static function fromDateTimeInterface(DateTimeInterface $datetime)
62
    {
63
        return new self($datetime->format('H:i:s.u'));
64
    }
65
66
    private function sanitizeFormatString(string $format) : string
67
    {
68
        return preg_replace('/(?<!\\\\)([rceIOPTZUdDjlNSwzWFmMntLoYy])/', '\\\\$1', $format);
69
    }
70
}
71