1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PubPeerFoundation\PublicationDataExtractor\Support; |
4
|
|
|
|
5
|
|
|
use Carbon\Carbon; |
6
|
|
|
|
7
|
|
|
class DateHelper |
8
|
|
|
{ |
9
|
|
|
public static function dateFromDateParts(array $parts) |
10
|
|
|
{ |
11
|
|
|
if (empty($parts)) { |
12
|
|
|
return ''; |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
return static::formatForParts( |
16
|
|
|
Carbon::createFromDate(...array_merge($parts, [1, 1, 1])), |
|
|
|
|
17
|
|
|
count($parts) |
18
|
|
|
); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public static function dateFromParseableFormat($formattedDate) |
22
|
|
|
{ |
23
|
|
|
return Carbon::parse($formattedDate)->format('Y-m-d'); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public static function dateFromPubDate($pubDateObject) |
27
|
|
|
{ |
28
|
|
|
if (! isset($pubDateObject->Year) || empty($pubDateObject->Year)) { |
29
|
|
|
return ''; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$month = static::getPubDateMonth($pubDateObject); |
33
|
|
|
|
34
|
|
|
return static::formatForParts(Carbon::create( |
35
|
|
|
(int) $pubDateObject->Year, |
36
|
|
|
(int) $month, |
37
|
|
|
isset($pubDateObject->Day) ? (int) $pubDateObject->Day : 1 |
38
|
|
|
), static::countObjectParts($pubDateObject)); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
protected static function getPubDateMonth($pubDateObject) |
42
|
|
|
{ |
43
|
|
|
if (! isset($pubDateObject->Month)) { |
44
|
|
|
return 1; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return ! is_numeric((string) $pubDateObject->Month) |
48
|
|
|
? Carbon::createFromFormat('M', (string) $pubDateObject->Month)->format('n') |
49
|
|
|
: $pubDateObject->Month; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected static function formatForParts($date, $count) |
53
|
|
|
{ |
54
|
|
|
$partsToFormat = [ |
55
|
|
|
1 => 'Y', |
56
|
|
|
2 => 'Y-m', |
57
|
|
|
3 => 'Y-m-d', |
58
|
|
|
]; |
59
|
|
|
|
60
|
|
|
return $date->format($partsToFormat[$count]); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected static function countObjectParts($pubDateObject) |
64
|
|
|
{ |
65
|
|
|
return array_reduce(['Year', 'Month', 'Day'], function ($carry, $datePart) use ($pubDateObject) { |
66
|
|
|
return isset($pubDateObject->$datePart) ? $carry + 1 : $carry; |
67
|
|
|
}, 0); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|