Completed
Push — master ( a304f8...463e36 )
by Andreu
02:23
created

UniversalTimestamp::fromSecondsTimestamp()   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 1
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
        $dtU = (int)$dateTime->format('u');
64
65 3
        return new UniversalTimestamp(
66 3
            $dateTime->getTimestamp()*1000 + (int)floor($dtU/1000),
67 3
            $dtU % 1000
68
        );
69
    }
70
71
    /**
72
     * @param int $secondsSinceEpoch
73
     * @return UniversalTimestamp
74
     */
75 2
    public static function fromSecondsTimestamp($secondsSinceEpoch)
76
    {
77 2
        return new UniversalTimestamp($secondsSinceEpoch*1000);
78
    }
79
80
    /**
81
     * @param int $millisSinceEpoch
82
     * @param int $micros
83
     * @return UniversalTimestamp
84
     */
85 4
    public static function fromMillisecondsTimestamp($millisSinceEpoch, $micros = 0)
86
    {
87 4
        return new UniversalTimestamp($millisSinceEpoch, $micros);
88
    }
89
90
    /**
91
     * @param mixed $dateObject   If it's an integer, then it's understood as milliseconds since epoch
92
     * @return UniversalTimestamp
93
     */
94 2
    public static function fromWhatever($dateObject) {
95 2
        if (null === $dateObject) {
96 1
            return static::now();
97 2
        } elseif (is_int($dateObject)) {
98 1
            return static::fromMillisecondsTimestamp($dateObject);
99
        } elseif ($dateObject instanceof UniversalTimestamp) {
100
            return $dateObject;
101
        } elseif ($dateObject instanceof \DateTimeInterface) {
102 1
            return static::fromDateTimeInterface($dateObject);
103
        } elseif ($dateObject instanceof \MongoDate) {
104
            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...
105
        } else {
106 1
            throw new JiffyException('The provided value cannot be interpreted as a timestamp');
107
        }
108
    }
109
110
    /**
111
     * @param UniversalTimestamp $otherTimestamp
112
     * @return boolean
113
     */
114 3
    public function isGreaterThan(UniversalTimestamp $otherTimestamp)
115
    {
116
        return (
117 3
            $this->millis > $otherTimestamp->millis ||
118 3
            $this->millis === $otherTimestamp->millis && $this->micros > $otherTimestamp->micros
119
        );
120
    }
121
122
    /**
123
     * @param int $seconds
124
     * @return UniversalTimestamp
125
     */
126 1
    public function addSeconds($seconds)
127
    {
128 1
        return new UniversalTimestamp($this->millis + 1000*$seconds, $this->micros);
129
    }
130
131
    /**
132
     * @param int $millis
133
     * @return UniversalTimestamp
134
     */
135 1
    public function addMilliseconds($millis)
136
    {
137 1
        return new UniversalTimestamp($this->millis + $millis, $this->micros);
138
    }
139
140
    /**
141
     * @return int
142
     */
143 8
    public function asSeconds()
144
    {
145 8
        return (int)floor($this->millis/1000);
146
    }
147
148
    /**
149
     * @return int
150
     */
151 3
    public function asMilliseconds()
152
    {
153 3
        return $this->millis;
154
    }
155
156
    /**
157
     * @return int
158
     */
159 1
    public function getRemainingMicroseconds()
160
    {
161 1
        return $this->micros;
162
    }
163
164
    /**
165
     * @param string|\DateTimeZone $tz
166
     * @return \DateTimeImmutable
167
     */
168 2
    public function asDateTimeInterface($tz = 'UTC')
169
    {
170 2
        $dateTime = new \DateTimeImmutable();
171
        $dateTime = $dateTime
172 2
            ->setTimestamp($this->asSeconds())
173 2
            ->setTimezone(is_string($tz) ? new \DateTimeZone($tz) : $tz);
174
175 2
        return new \DateTimeImmutable(
176 2
            $dateTime->format('Y-m-d\TH:i:s').'.'.
177 2
            sprintf("%'.03d", $this->millis%1000).sprintf("%'.03d", $this->micros).
178 2
            $dateTime->format('O')
179
        );
180
    }
181
182
    /**
183
     * @param string $format
184
     * @param string|\DateTimeZone $tz
185
     * @param bool $showMillis
186
     * @param bool $stripTz
187
     * @return string
188
     */
189 2
    public function asFormattedString(
190
        $format = \DateTime::ISO8601, $tz = 'UTC', $showMillis = false, $stripTz = false
191
    )
192
    {
193 2
        $r = $this->asDateTimeInterface($tz)->format($format);
194
195 2
        if (\DateTime::ISO8601 === $format && $showMillis) {
196 1
            $rParts = preg_split('/\+/', $r);
197 1
            $r = $rParts[0].'.'.((string)$this->millis%1000).($stripTz?'':('+'.$rParts[1]));
198 2
        } elseif (\DateTime::ISO8601 === $format && $stripTz) {
199 1
            $rParts = preg_split('/\+/', $r);
200 1
            $r = $rParts[0];
201
        }
202
203 2
        return $r;
204
    }
205
206
    /**
207
     * @return string
208
     */
209 1
    public function __toString()
210
    {
211 1
        return $this->asFormattedString();
212
    }
213
}
214