forked from lexik/LexikTranslationBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCleanTranslationCacheListener.php
More file actions
84 lines (73 loc) · 2.7 KB
/
Copy pathCleanTranslationCacheListener.php
File metadata and controls
84 lines (73 loc) · 2.7 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
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace Lexik\Bundle\TranslationBundle\EventDispatcher;
use Lexik\Bundle\TranslationBundle\Manager\LocaleManagerInterface;
use Lexik\Bundle\TranslationBundle\Storage\StorageInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Finder\Finder;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* @author Cédric Girard <c.girard@lexik.fr>
*/
class CleanTranslationCacheListener
{
public function __construct(
private readonly StorageInterface $storage,
private readonly TranslatorInterface $translator,
private readonly string$cacheDirectory,
private readonly LocaleManagerInterface $localeManager,
private readonly int $cacheInterval,
) {
}
public function onKernelRequest(RequestEvent $event)
{
if ($event->isMainRequest() && $this->isCacheExpired()) {
$lastUpdateTime = $this->storage->getLatestUpdatedAt();
if ($lastUpdateTime instanceof \DateTime) {
$this->checkCacheFolder();
$finder = new Finder();
$finder->files()
->in($this->cacheDirectory.'/translations')
->date('< '.$lastUpdateTime->format('Y-m-d H:i:s'));
if ($finder->count() > 0) {
$this->translator->removeLocalesCacheFiles($this->localeManager->getLocales());
}
}
}
}
/**
* Checks if cache has expired
*
* @return boolean
*/
private function isCacheExpired()
{
if (empty($this->cacheInterval)) {
return true;
}
$cache_file = $this->cacheDirectory.'/translations/cache_timestamp';
$cache_dir =$this->cacheDirectory.'/translations';
if ('\\' === DIRECTORY_SEPARATOR) {
$cache_file = strtr($cache_file, '/', '\\');
$cache_dir = strtr($cache_dir, '/', '\\');
}
if (!\is_dir($cache_dir) && !\mkdir($cache_dir, 0777, true) && !\is_dir($cache_dir)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $cache_dir));
}
if (!\file_exists($cache_file)) {
\touch($cache_file);
return true;
}
$expired = false;
if ((\time() - \filemtime($cache_file)) > $this->cacheInterval) {
\file_put_contents($cache_file, \time());
$expired = true;
}
return $expired;
}
private function checkCacheFolder()
{
if (!is_dir($dirName = $this->cacheDirectory.'/translations') && !mkdir($dirName) && !is_dir($dirName)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dirName));
}
}
}