|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Marek\SiteAccessAwareDateFormatBundle\Core; |
|
6
|
|
|
|
|
7
|
|
|
use DateTimeInterface; |
|
8
|
|
|
use eZ\Publish\Core\MVC\ConfigResolverInterface; |
|
9
|
|
|
use Marek\SiteAccessAwareDateFormatBundle\API\DateFormatter; |
|
10
|
|
|
use Marek\SiteAccessAwareDateFormatBundle\DependencyInjection\Configuration; |
|
11
|
|
|
use RuntimeException; |
|
12
|
|
|
|
|
13
|
|
|
final class SiteAccessAwareFormatter |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var \Marek\SiteAccessAwareDateFormatBundle\API\DateFormatter |
|
17
|
|
|
*/ |
|
18
|
|
|
private $defaultDateFormatter; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var \eZ\Publish\Core\MVC\ConfigResolverInterface |
|
22
|
|
|
*/ |
|
23
|
|
|
private $configResolver; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* SiteAccessAwareFormatter constructor. |
|
27
|
|
|
* |
|
28
|
|
|
* @param \Marek\SiteAccessAwareDateFormatBundle\API\DateFormatter $defaultDateFormatter |
|
29
|
|
|
* @param \eZ\Publish\Core\MVC\ConfigResolverInterface $configResolver |
|
30
|
|
|
*/ |
|
31
|
|
|
public function __construct(DateFormatter $defaultDateFormatter, ConfigResolverInterface $configResolver) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->defaultDateFormatter = $defaultDateFormatter; |
|
34
|
|
|
$this->configResolver = $configResolver; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @inheritdoc |
|
39
|
|
|
*/ |
|
40
|
|
|
public function format(DateTimeInterface $date, string $dateFormatIdentifier): string |
|
41
|
|
|
{ |
|
42
|
|
|
if ($dateFormatIdentifier === DateFormatter::FORMAT_DEFAULT) { |
|
43
|
|
|
return $this->defaultDateFormatter->format($date, $dateFormatIdentifier); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
if (!$this->configResolver->hasParameter('formats', Configuration::TREE_ROOT)) { |
|
47
|
|
|
throw new RuntimeException( |
|
48
|
|
|
sprintf('Configuration %s is missing formats option.', Configuration::TREE_ROOT) |
|
49
|
|
|
); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$formats = $this->configResolver->getParameter('formats', Configuration::TREE_ROOT); |
|
53
|
|
|
|
|
54
|
|
|
if (!array_key_exists($dateFormatIdentifier, $formats)) { |
|
55
|
|
|
throw new RuntimeException( |
|
56
|
|
|
sprintf('Given datetime format %s does not exist in configuration.', $dateFormatIdentifier) |
|
57
|
|
|
); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return $date->format( |
|
61
|
|
|
$formats[$dateFormatIdentifier] |
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|