Completed
Push — master ( c734df...a43bb8 )
by Neomerx
04:02
created

DateTime::createFromDateTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 4
cp 1
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php namespace Limoncello\Flute\Types;
2
3
/**
4
 * Copyright 2015-2018 [email protected]
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
use DateTimeImmutable;
20
use DateTimeInterface;
21
use Exception;
22
use JsonSerializable;
23
24
/**
25
 * Wrapper class for `DateTimeInterface` value with JSON serialization support.
26
 *
27
 * @package Limoncello\Flute
28
 */
29
class DateTime extends DateTimeImmutable implements JsonSerializable
30
{
31
    /** DateTime format */
32
    const JSON_API_FORMAT = \DateTime::ISO8601;
33
34
    /**
35
     * @param DateTimeInterface $dateTime
36
     *
37
     * @return DateTime
38
     *
39
     * @throws Exception
40
     */
41 37
    public static function createFromDateTime(DateTimeInterface $dateTime): self
42
    {
43 37
        $utcTimestamp = $dateTime->getTimestamp();
44
45
        // yes, PHP DateTime can accept integer timestamp only as a string ¯\_( ͡° ͜ʖ ͡°)_/¯
46 37
        $result = (new self("@$utcTimestamp"))->setTimezone($dateTime->getTimezone());
47
48 37
        return $result;
49
    }
50
51
    /**
52
     * @inheritdoc
53
     */
54 19
    public function jsonSerialize()
55
    {
56 19
        return $this->format(static::JSON_API_FORMAT);
57
    }
58
}
59