Completed
Push — master ( 94d22b...a304f8 )
by Andreu
02:15
created

UniversalTimestamp::asSeconds()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 8 and the first side effect is on line 8.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
4
namespace Litipk\Jiffy;
5
6
7 1
if (!extension_loaded('mongo')) {
8
    trait TsExtension {};
9
} else {
10
    trait TsExtension { use MongoAdapter; };
0 ignored issues
show
Comprehensibility Best Practice introduced by
The type Litipk\Jiffy\TsExtension has been defined more than once; this definition is ignored, only the first definition in this file (L8-8) is considered.

This check looks for classes that have been defined more than once in the same file.

If you can, we would recommend to use standard object-oriented programming techniques. For example, to avoid multiple types, it might make sense to create a common interface, and then multiple, different implementations for that interface.

This also has the side-effect of providing you with better IDE auto-completion, static analysis and also better OPCode caching from PHP.

Loading history...
Coding Style Compatibility introduced by
Each trait must be in a file by itself

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
11
}
12
13
14
/**
15
 * Class UniversalTimestamp
16
 * @package Litipk\Jiffy
17
 */
18
class UniversalTimestamp
0 ignored issues
show
Coding Style Compatibility introduced by
Each trait must be in a file by itself

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
19
{
20
    use TsExtension;
21
22
    /** @var int */
23
    private $millis;
24
25
    /** @var int */
26
    private $micros;
27
28
    /**
29
     * Constructor.
30
     *
31
     * @param integer $millisSinceEpoch
32
     * @param integer $micros
33
     */
34 13
    private function __construct($millisSinceEpoch, $micros = 0)
35
    {
36 13
        if ($millisSinceEpoch < 0 || $micros < 0) {
37 1
            throw new JiffyException('The number of milliseconds and microseconds must be positive');
38
        }
39
40 12
        $this->millis = $millisSinceEpoch + (int)($micros/1000);
41 12
        $this->micros = $micros % 1000;
42 12
    }
43
44
    /**
45
     * @return UniversalTimestamp
46
     */
47 7
    public static function now()
48
    {
49 7
        $ts_parts = explode(' ', microtime());
50
51 7
        return new UniversalTimestamp(
52 7
            (int)floor($ts_parts[0]*1000) + (int)$ts_parts[1]*1000,  // Millis
53 7
            ((int)round($ts_parts[0]*1000000))%1000                  // Micros
54
        );
55
    }
56
57
    /**
58
     * @param \DateTimeInterface $dateTime
59
     * @return UniversalTimestamp
60
     */
61 3
    public static function fromDateTimeInterface(\DateTimeInterface $dateTime)
62
    {
63 3
        return new UniversalTimestamp($dateTime->getTimestamp()*1000, 0);
64
    }
65
66
    /**
67
     * @param int $secondsSinceEpoch
68
     * @return UniversalTimestamp
69
     */
70 2
    public static function fromSecondsTimestamp($secondsSinceEpoch)
71
    {
72 2
        return new UniversalTimestamp($secondsSinceEpoch*1000);
73
    }
74
75
    /**
76
     * @param int $millisSinceEpoch
77
     * @param int $micros
78
     * @return UniversalTimestamp
79
     */
80 4
    public static function fromMillisecondsTimestamp($millisSinceEpoch, $micros = 0)
81
    {
82 4
        return new UniversalTimestamp($millisSinceEpoch, $micros);
83
    }
84
85
    /**
86
     * @param mixed $dateObject   If it's an integer, then it's understood as milliseconds since epoch
87
     * @return UniversalTimestamp
88
     */
89 2
    public static function fromWhatever($dateObject) {
90 2
        if (null === $dateObject) {
91 1
            return static::now();
92 2
        } elseif (is_int($dateObject)) {
93 1
            return static::fromMillisecondsTimestamp($dateObject);
94
        } elseif ($dateObject instanceof UniversalTimestamp) {
95
            return $dateObject;
96
        } elseif ($dateObject instanceof \DateTimeInterface) {
97 1
            return static::fromDateTimeInterface($dateObject);
98
        } elseif ($dateObject instanceof \MongoDate) {
99
            return static::fromMongoDate($dateObject);
0 ignored issues
show
Bug introduced by
The method fromMongoDate() does not seem to exist on object<Litipk\Jiffy\UniversalTimestamp>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
100
        } else {
101 1
            throw new JiffyException('The provided value cannot be interpreted as a timestamp');
102
        }
103
    }
104
105
    /**
106
     * @param UniversalTimestamp $otherTimestamp
107
     * @return boolean
108
     */
109 3
    public function isGreaterThan(UniversalTimestamp $otherTimestamp)
110
    {
111
        return (
112 3
            $this->millis > $otherTimestamp->millis ||
113 3
            $this->millis === $otherTimestamp->millis && $this->micros > $otherTimestamp->micros
114
        );
115
    }
116
117
    /**
118
     * @param int $seconds
119
     * @return UniversalTimestamp
120
     */
121 1
    public function addSeconds($seconds)
122
    {
123 1
        return new UniversalTimestamp($this->millis + 1000*$seconds, $this->micros);
124
    }
125
126
    /**
127
     * @param int $millis
128
     * @return UniversalTimestamp
129
     */
130 1
    public function addMilliseconds($millis)
131
    {
132 1
        return new UniversalTimestamp($this->millis + $millis, $this->micros);
133
    }
134
135
    /**
136
     * @return int
137
     */
138 8
    public function asSeconds()
139
    {
140 8
        return (int)floor($this->millis/1000);
141
    }
142
143
    /**
144
     * @return int
145
     */
146 3
    public function asMilliseconds()
147
    {
148 3
        return $this->millis;
149
    }
150
151
    /**
152
     * @return int
153
     */
154 1
    public function getRemainingMicroseconds()
155
    {
156 1
        return $this->micros;
157
    }
158
159
    /**
160
     * @param string|\DateTimeZone $tz
161
     * @return \DateTimeImmutable
162
     */
163 2
    public function asDateTimeInterface($tz = 'UTC')
164
    {
165 2
        $dateTime = new \DateTimeImmutable();
166
        $dateTime = $dateTime
167 2
            ->setTimestamp($this->asSeconds())
168 2
            ->setTimezone(is_string($tz) ? new \DateTimeZone($tz) : $tz);
169
170 2
        return new \DateTimeImmutable(
171 2
            $dateTime->format('Y-m-d\TH:i:s').'.'.
172 2
            sprintf("%'.03d", $this->millis%1000).sprintf("%'.03d", $this->micros).
173 2
            $dateTime->format('O')
174
        );
175
    }
176
177
    /**
178
     * @param string $format
179
     * @param string|\DateTimeZone $tz
180
     * @param bool $showMillis
181
     * @param bool $stripTz
182
     * @return string
183
     */
184 2
    public function asFormattedString(
185
        $format = \DateTime::ISO8601, $tz = 'UTC', $showMillis = false, $stripTz = false
186
    )
187
    {
188 2
        $r = $this->asDateTimeInterface($tz)->format($format);
189
190 2
        if (\DateTime::ISO8601 === $format && $showMillis) {
191 1
            $rParts = preg_split('/\+/', $r);
192 1
            $r = $rParts[0].'.'.((string)$this->millis%1000).($stripTz?'':('+'.$rParts[1]));
193 2
        } elseif (\DateTime::ISO8601 === $format && $stripTz) {
194 1
            $rParts = preg_split('/\+/', $r);
195 1
            $r = $rParts[0];
196
        }
197
198 2
        return $r;
199
    }
200
201
    /**
202
     * @return string
203
     */
204 1
    public function __toString()
205
    {
206 1
        return $this->asFormattedString();
207
    }
208
}
209