Timestamp::__construct()   A
last analyzed

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 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
ccs 2
cts 2
cp 1
crap 1
rs 10
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('The timestamp to normalise must be one of ' . $supportedClasses . ' but it is not an object');
53
        }
54
55 5
        switch (get_class($this->t)) {
56 5
            case 'MongoTimestamp':
57
                return (int) $this->t->__toString();
58
59 5
            case 'MongoDate':
60
                return $this->t->sec;
61
62 5
            case 'MongoDB\BSON\Timestamp':
63 1
                return $this->t->getTimestamp();
64
65 4
            case 'MongoDB\BSON\UTCDateTime':
66 1
                return (int) $this->t->toDateTime()->format('U');
67
        }
68
69 3
        if ($this->t instanceof \DateTimeInterface) {
70 2
            return $this->t->getTimestamp();
71
        }
72
73 1
        throw new \DomainException('The normalised timestamp must be one of ' . $supportedClasses);
74
    }
75
76
    public function __toString(): string
77
    {
78
        return (string) $this->getTimestamp();
79
    }
80
}
81