1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the DateTime library. |
4
|
|
|
* |
5
|
|
|
* (c) Artem Henvald <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
declare(strict_types=1); |
12
|
|
|
|
13
|
|
|
namespace Fresh\DateTime; |
14
|
|
|
|
15
|
|
|
use Fresh\DateTime\Exception\UnexpectedValueException; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* DateTimeCloner. |
19
|
|
|
* |
20
|
|
|
* @author Artem Henvald <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
class DateTimeCloner |
23
|
|
|
{ |
24
|
|
|
private const DATE_FORMAT_FOR_CLONE = 'Y-m-d H:i:s e'; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param \DateTimeInterface $originalDate |
28
|
|
|
* |
29
|
|
|
* @throws UnexpectedValueException |
30
|
|
|
* |
31
|
|
|
* @return \DateTime |
32
|
|
|
*/ |
33
|
|
|
public static function cloneIntoDateTime(\DateTimeInterface $originalDate): \DateTime |
34
|
|
|
{ |
35
|
|
|
$date = \DateTime::createFromFormat( |
36
|
|
|
self::DATE_FORMAT_FOR_CLONE, |
37
|
|
|
$originalDate->format(self::DATE_FORMAT_FOR_CLONE), |
38
|
|
|
$originalDate->getTimezone() |
39
|
|
|
); |
40
|
|
|
|
41
|
|
|
if (!$date instanceof \DateTime) { |
42
|
|
|
throw new UnexpectedValueException(\sprintf('Could not create %s object', \DateTime::class)); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $date; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param \DateTimeInterface $originalDate |
50
|
|
|
* |
51
|
|
|
* @throws UnexpectedValueException |
52
|
|
|
* |
53
|
|
|
* @return \DateTimeImmutable |
54
|
|
|
*/ |
55
|
|
|
public static function cloneIntoDateTimeImmutable(\DateTimeInterface $originalDate): \DateTimeImmutable |
56
|
|
|
{ |
57
|
|
|
$date = \DateTimeImmutable::createFromFormat( |
58
|
|
|
self::DATE_FORMAT_FOR_CLONE, |
59
|
|
|
$originalDate->format(self::DATE_FORMAT_FOR_CLONE), |
60
|
|
|
$originalDate->getTimezone() |
61
|
|
|
); |
62
|
|
|
|
63
|
|
|
if (!$date instanceof \DateTimeImmutable) { |
64
|
|
|
throw new UnexpectedValueException(\sprintf('Could not create %s object', \DateTimeImmutable::class)); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $date; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|