-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLocalizedStringParser.php
More file actions
71 lines (63 loc) · 2.44 KB
/
LocalizedStringParser.php
File metadata and controls
71 lines (63 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
declare(strict_types=1);
namespace AssoConnect\PHPDate;
use AssoConnect\PHPDate\Exception\UnknownPatternException;
use AssoConnect\PHPDate\Exception\UnsupportedLocalException;
use IntlDateFormatter;
class LocalizedStringParser
{
/**
* Returns an AbsoluteDate instance from a formatted string like 9/1/23 for September, 1st 2023 in the USA
* @param string $date Formatted date
* @param string $locale Locale used to format the date (both en-US & en_US patterns are supported)
*/
public function create(string $date, string $locale): AbsoluteDate
{
// ⚠️ IntlDateFormatter & DateTimeInterface don't use the same patterns
$parts = \Safe\array_combine(
explode('/', $this->getPatternFromLocale($locale)), // IntlDateFormatter pattern
explode('/', $date)
);
$orderedDateParts = ['', '', ''];
$patternParts = ['', '', '']; // DateTimeInterface pattern
foreach ($parts as $pattern => $value) {
switch ($pattern) {
case 'd': // Day without leading 0
case 'dd': // Day with leading 0
$orderedDateParts[2] = str_pad($value, 2, '0', STR_PAD_LEFT);
$patternParts[2] = 'd';
break;
case 'M': // Month without leading 0
case 'MM': // Month with leading 0
$orderedDateParts[1] = str_pad($value, 2, '0', STR_PAD_LEFT);
$patternParts[1] = 'm';
break;
case 'y': // Year on 4 digits
case 'yy': // Year on 2 digits
case 'yyyy': // Year on 4 digits
$orderedDateParts[0] = $value;
$patternParts[0] = (2 === strlen($value)) ? 'y' : 'Y';
break;
default:
throw new UnknownPatternException($pattern);
}
}
return new AbsoluteDate(
implode('-', $orderedDateParts),
implode('-', $patternParts)
);
}
public function getPatternFromLocale(string $locale): string
{
$formatter = new IntlDateFormatter(
$locale,
IntlDateFormatter::SHORT,
IntlDateFormatter::NONE,
);
$pattern = $formatter->getPattern();
if (false === $pattern) {
throw new UnsupportedLocalException($locale);
}
return $pattern;
}
}