Completed
Push — master ( d3dbff...99cdbf )
by Andreu
05:03
created

UniversalTimestamp   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 221
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 96.3%

Importance

Changes 9
Bugs 3 Features 3
Metric Value
wmc 32
c 9
b 3
f 3
lcom 2
cbo 2
dl 0
loc 221
ccs 78
cts 81
cp 0.963
rs 9.6

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 3
A now() 0 9 1
A fromDateTimeInterface() 0 9 1
A fromStringTimestamp() 0 12 3
A fromSecondsTimestamp() 0 4 1
A fromMillisecondsTimestamp() 0 4 1
B fromWhatever() 0 19 8
A isGreaterThan() 0 7 3
A addSeconds() 0 7 1
A addMilliseconds() 0 7 1
A asSeconds() 0 4 1
A asMilliseconds() 0 4 1
A getRemainingMicroseconds() 0 4 1
A asDateTimeInterface() 0 11 2
A asFormattedString() 0 12 3
A __toString() 0 4 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') && extension_loaded('mongodb')) {
8
    trait TsExtension { use MongoAdapter; use MongodbAdapter; };
9 1
} elseif (extension_loaded('mongo')) {
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
} elseif (extension_loaded('mongodb')) {
12
    trait TsExtension { use MongodbAdapter; };
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...
13
} else {
14
    trait TsExtension {};
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...
15
}
16
17
18
/**
19
 * Class UniversalTimestamp
20
 * @package Litipk\Jiffy
21
 */
22
final 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...
23
{
24
    const ISO8601_WITH_MILLISECONDS = '_ISO8601_WITH_MILLIS_';
25
    const ISO8601_WITH_MILLISECONDS_WITHOUT_TZ = '_ISO8601_WITH_MILLIS_WITHOUT_TZ';
26
    const ISO8601_WITH_MICROSECONDS = 'Y-m-d\TH:i:s.uO';
27
    const ISO8601_WITH_MICROSECONDS_WITHOUT_TZ = 'Y-m-d\TH:i:s.u';
28
29
    use TsExtension;
30
31
    /** @var int */
32
    private $millis;
33
34
    /** @var int */
35
    private $micros;
36
37
    /**
38
     * Constructor.
39
     *
40
     * @param integer $millisSinceEpoch
41
     * @param integer $micros
42
     */
43 17
    private function __construct($millisSinceEpoch, $micros = 0)
44
    {
45 17
        if ($millisSinceEpoch < 0 || $micros < 0) {
46 1
            throw new JiffyException('The number of milliseconds and microseconds must be positive');
47
        }
48
49 16
        $this->millis = $millisSinceEpoch + (int)($micros/1000);
50 16
        $this->micros = $micros % 1000;
51 16
    }
52
53
    /**
54
     * @return UniversalTimestamp
55
     */
56 10
    public static function now()
57
    {
58 10
        $ts_parts = explode(' ', microtime());
59
60 10
        return new UniversalTimestamp(
61 10
            (int)floor($ts_parts[0]*1000) + (int)$ts_parts[1]*1000,  // Millis
62 10
            ((int)round($ts_parts[0]*1000000))%1000                  // Micros
63 10
        );
64
    }
65
66
    /**
67
     * @param \DateTimeInterface $dateTime
68
     * @return UniversalTimestamp
69
     */
70 3
    public static function fromDateTimeInterface(\DateTimeInterface $dateTime)
71
    {
72 3
        $dtU = (int)$dateTime->format('u');
73
74 3
        return new UniversalTimestamp(
75 3
            $dateTime->getTimestamp()*1000 + (int)floor($dtU/1000),
76
            $dtU % 1000
77 3
        );
78
    }
79
80
    /**
81
     * @param string $strTimestamp
82
     * @param string $tz
83
     * @return UniversalTimestamp
84
     */
85 1
    public static function fromStringTimestamp($strTimestamp, $tz = 'UTC')
86
    {
87
        try {
88 1
            $dt = new \DateTimeImmutable(
89 1
                $strTimestamp,
90 1
                ($tz instanceof \DateTimeZone) ? $tz : new \DateTimeZone($tz)
91 1
            );
92 1
        } catch (\Exception $e) {
93 1
            throw new JiffyException('The provided value cannot be interpreted as a timestamp');
94
        }
95
        return self::fromDateTimeInterface($dt);
96
    }
97
98
    /**
99
     * @param int $secondsSinceEpoch
100
     * @return UniversalTimestamp
101
     */
102 1
    public static function fromSecondsTimestamp($secondsSinceEpoch)
103
    {
104 1
        return new UniversalTimestamp($secondsSinceEpoch*1000);
105
    }
106
107
    /**
108
     * @param int $millisSinceEpoch
109
     * @param int $micros
110
     * @return UniversalTimestamp
111
     */
112 9
    public static function fromMillisecondsTimestamp($millisSinceEpoch, $micros = 0)
113
    {
114 9
        return new UniversalTimestamp($millisSinceEpoch, $micros);
115
    }
116
117
    /**
118
     * @param mixed $dateObject   If it's an integer, then it's understood as milliseconds since epoch
119
     * @return UniversalTimestamp
120
     */
121 2
    public static function fromWhatever($dateObject) {
122 2
        if (null === $dateObject) {
123 1
            return self::now();
124 2
        } elseif (is_int($dateObject)) {
125 1
            return self::fromMillisecondsTimestamp($dateObject);
126 2
        } elseif (is_string($dateObject)) {
127 1
            return self::fromStringTimestamp($dateObject);
128 1
        } elseif ($dateObject instanceof UniversalTimestamp) {
129
            return $dateObject;
130 1
        } elseif ($dateObject instanceof \DateTimeInterface) {
131 1
            return self::fromDateTimeInterface($dateObject);
132 1
        } elseif ($dateObject instanceof \MongoDate) {
133 1
            return self::fromMongoDate($dateObject);
134 1
        } elseif ($dateObject instanceof \MongoDB\BSON\UTCDatetime) {
0 ignored issues
show
Bug introduced by
The class MongoDB\BSON\UTCDatetime does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
135 1
            return self::fromMongodbUTCDateTime($dateObject);
136
        } else {
137
            throw new JiffyException('The provided value cannot be interpreted as a timestamp');
138
        }
139
    }
140
141
    /**
142
     * @param UniversalTimestamp $otherTimestamp
143
     * @return boolean
144
     */
145 3
    public function isGreaterThan(UniversalTimestamp $otherTimestamp)
146
    {
147
        return (
148 3
            $this->millis > $otherTimestamp->millis ||
149 3
            $this->millis === $otherTimestamp->millis && $this->micros > $otherTimestamp->micros
150 3
        );
151
    }
152
153
    /**
154
     * @param int $seconds
155
     * @return UniversalTimestamp
156
     */
157 1
    public function addSeconds($seconds)
158
    {
159 1
        $copy = clone $this;
160 1
        $copy->millis += 1000*$seconds;
161
162 1
        return $copy;
163
    }
164
165
    /**
166
     * @param int $millis
167
     * @return UniversalTimestamp
168
     */
169 1
    public function addMilliseconds($millis)
170
    {
171 1
        $copy = clone $this;
172 1
        $copy->millis += $millis;
173
174 1
        return $copy;
175
    }
176
177
    /**
178
     * @return int
179
     */
180 10
    public function asSeconds()
181
    {
182 10
        return (int)floor($this->millis/1000);
183
    }
184
185
    /**
186
     * @return int
187
     */
188 9
    public function asMilliseconds()
189
    {
190 9
        return $this->millis;
191
    }
192
193
    /**
194
     * @return int
195
     */
196 1
    public function getRemainingMicroseconds()
197
    {
198 1
        return $this->micros;
199
    }
200
201
    /**
202
     * @param string|\DateTimeZone $tz
203
     * @return \DateTimeImmutable
204
     */
205 2
    public function asDateTimeInterface($tz = 'UTC')
206
    {
207 2
        $dateTime = new \DateTimeImmutable('@'.((string)$this->asSeconds()));
208 2
        $dateTime = $dateTime->setTimezone(is_string($tz) ? new \DateTimeZone($tz) : $tz);
209
210 2
        return new \DateTimeImmutable(
211 2
            $dateTime->format('Y-m-d\TH:i:s').'.'.
212 2
            sprintf("%03d", $this->millis%1000).sprintf("%03d", $this->micros).
213 2
            $dateTime->format('O')
214 2
        );
215
    }
216
217
    /**
218
     * @param string $format
219
     * @param string|\DateTimeZone $tz
220
     * @return string
221
     */
222 2
    public function asFormattedString($format = self::ISO8601_WITH_MICROSECONDS, $tz = 'UTC')
223
    {
224 2
        if (self::ISO8601_WITH_MILLISECONDS === $format) {
225 1
            $rParts = preg_split('/\+/', $this->asDateTimeInterface($tz)->format(\DateTime::ISO8601));
226 1
            return $rParts[0].'.'.((string)$this->millis%1000).'+'.$rParts[1];
227 2
        } elseif (self::ISO8601_WITH_MILLISECONDS_WITHOUT_TZ === $format) {
228 1
            $rParts = preg_split('/\+/', $this->asDateTimeInterface($tz)->format(\DateTime::ISO8601));
229 1
            return $rParts[0].'.'.((string)$this->millis%1000);
230
        } else {
231 2
            return $this->asDateTimeInterface($tz)->format($format);
232
        }
233
    }
234
235
    /**
236
     * @return string
237
     */
238 1
    public function __toString()
239
    {
240 1
        return $this->asFormattedString();
241
    }
242
}
243