1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Surfnet\Stepup\DateTime; |
4
|
|
|
|
5
|
|
|
use DateTime as CoreDateTime; |
6
|
|
|
use DateTimeZone; |
7
|
|
|
use Psr\Log\LoggerInterface; |
8
|
|
|
use Surfnet\Stepup\Exception\InvalidArgumentException; |
9
|
|
|
|
10
|
|
|
class UtcDateTimeFactory |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Allows for mocking of time. |
14
|
|
|
* |
15
|
|
|
* @var UtcDateTime|null |
16
|
|
|
*/ |
17
|
|
|
private static $now; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var LoggerInterface|null |
21
|
|
|
*/ |
22
|
|
|
public static $logger; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @return UtcDateTime |
26
|
|
|
*/ |
27
|
|
|
public static function now() |
28
|
|
|
{ |
29
|
|
|
return self::$now ?: new UtcDateTime(new CoreDateTime('now', new DateTimeZone('UTC'))); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param string $string A date-time string formatted using `self::FORMAT` (eg. '2014-11-26T15:20:43+01:00'). |
34
|
|
|
* @return UtcDateTime |
35
|
|
|
*/ |
36
|
|
|
public static function fromString($string) |
37
|
|
|
{ |
38
|
|
|
if (!is_string($string)) { |
39
|
|
|
InvalidArgumentException::invalidType('string', 'dateTime', $string); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$dateTime = CoreDateTime::createFromFormat(UtcDateTime::FORMAT, $string); |
43
|
|
|
|
44
|
|
|
if ($dateTime === false) { |
45
|
|
|
throw new InvalidArgumentException('Date-time string could not be parsed: is it formatted correctly?'); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return static::createFromTimezonedUtcDateTime($dateTime); |
|
|
|
|
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @deprecated UTC datetimes should be enforced on input. |
53
|
|
|
* @param CoreDateTime $dateTime |
54
|
|
|
* @return UtcDateTime |
55
|
|
|
*/ |
56
|
|
|
public static function createFromTimezonedUtcDateTime(CoreDateTime $dateTime) |
57
|
|
|
{ |
58
|
|
|
if ($dateTime->getOffset() === 0) { |
59
|
|
|
return new UtcDateTime($dateTime); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$incorrectOffset = $dateTime->getOffset(); |
63
|
|
|
$dateTime->setTimeZone(new DateTimeZone('UTC')); |
64
|
|
|
|
65
|
|
|
if (!static::$logger) { |
66
|
|
|
return new UtcDateTime($dateTime); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
static::$logger->warning(sprintf('Creating Stepup DateTime, expected no timezone offset, but got offset "%s"', $incorrectOffset)); |
|
|
|
|
70
|
|
|
|
71
|
|
|
return new UtcDateTime($dateTime); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
This method has been deprecated. The supplier of the class has supplied an explanatory message.
The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.