Completed
Push — master ( 1b8fb3...8ace2b )
by Douglas
11s
created

Timestamp::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the AntiMattr MongoDB Migrations Library, a library by Matthew Fitzgerald.
5
 *
6
 * (c) 2014 Matthew Fitzgerald
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace AntiMattr\MongoDB\Migrations\Configuration;
13
14
/**
15
 * This class is to normalise the potential values from the 't' version
16
 * attribute.
17
 *
18
 * @author Douglas Reith <[email protected]>
19
 */
20
class Timestamp
21
{
22
    private $t;
23
24
    /**
25
     * @param mixed $t
26
     */
27 6
    public function __construct($t)
28
    {
29 6
        $this->t = $t;
30 6
    }
31
32
    /**
33
     * Normalise based on the different options for backward/forward
34
     * compatibility.
35
     *
36
     * @return int Time in seconds since 1970
37
     */
38 6
    public function getTimestamp(): int
39
    {
40 6
        $supportedClasses = implode(
41 6
            ', ',
42
            [
43 6
                '\MongoTimestamp',
44
                '\MongoDate',
45
                '\MongoDB\BSON\Timestamp',
46
                '\MongoDB\BSON\UTCDateTime',
47
                '\DateTimeInterface',
48
            ]
49
        );
50
51 6
        if (!$this->t || !is_object($this->t)) {
52 1
            throw new \DomainException(
53 1
                'The timestamp to normalise must be one of ' . $supportedClasses . ' but it is not an object'
54
            );
55
        }
56
57 5
        switch (get_class($this->t)) {
58 5
            case 'MongoTimestamp':
59
                return (int) $this->t->__toString();
60
61 5
            case 'MongoDate':
62
                return $this->t->sec;
63
64 5
            case 'MongoDB\BSON\Timestamp':
65 1
                return $this->t->getTimestamp();
66
67 4
            case 'MongoDB\BSON\UTCDateTime':
68 1
                return (int) $this->t->toDateTime()->format('U');
69
        }
70
71 3
        if ($this->t instanceof \DateTimeInterface) {
72 2
            return $this->t->getTimestamp();
73
        }
74
75 1
        throw new \DomainException(
76 1
            'The normalised timestamp must be one of ' . $supportedClasses
77
        );
78
    }
79
80
    /**
81
     * @return string
82
     */
83 1
    public function __toString(): string
84
    {
85 1
        return (string) $this->getTimestamp();
86
    }
87
}
88