forked from 123inkt/internationalization
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRelativeDateFallbackService.php
58 lines (46 loc) · 2.01 KB
/
RelativeDateFallbackService.php
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
<?php
declare(strict_types=1);
namespace DR\Internationalization\Date;
use DateTimeImmutable;
use DateTimeInterface;
use RuntimeException;
class RelativeDateFallbackService
{
private const MAX_TRANSLATABLE_DAYS_AMOUNT = 4;
private RelativeDateFormatterFactory $relativeFormatterFactory;
public function __construct(?RelativeDateFormatterFactory $relativeFormatterFactory = null)
{
$this->relativeFormatterFactory = $relativeFormatterFactory ?? new RelativeDateFormatterFactory();
}
public function getFallbackResult(
string $locale,
DateTimeInterface $dateTime,
RelativeDateFormatOptions $relativeOptions
): RelativeDateFallbackResult {
$currentDateTime = (new DateTimeImmutable())->setTime(0, 0);
if ($dateTime->diff($currentDateTime)->d > self::MAX_TRANSLATABLE_DAYS_AMOUNT
|| $relativeOptions->getRelativeDaysAmount() === 0
|| $relativeOptions->getRelativeDaysAmount() === null
|| $dateTime->diff($currentDateTime)->d > $relativeOptions->getRelativeDaysAmount()
) {
return new RelativeDateFallbackResult(true);
}
$relativeDateFormatter = $this->relativeFormatterFactory->createRelativeFull($locale);
$fullDateFormatter = $this->relativeFormatterFactory->createFull($locale);
$relativeDate = $relativeDateFormatter->format($dateTime);
$fullDate = $fullDateFormatter->format($dateTime);
if ($relativeDate === false) {
throw new RuntimeException(
sprintf(
'An error occurred while trying to parse the relative date. Error code: %s, %s',
$relativeDateFormatter->getErrorCode(),
$relativeDateFormatter->getErrorMessage()
)
);
}
if ($relativeDate === $fullDate) {
return new RelativeDateFallbackResult(true);
}
return new RelativeDateFallbackResult(false, $relativeDate);
}
}