Skip to content

Instantly share code, notes, and snippets.

@koemeet
Last active January 19, 2017 16:55
Show Gist options
  • Save koemeet/0c24ba7957622ed4ee804620b4e0fe43 to your computer and use it in GitHub Desktop.
Save koemeet/0c24ba7957622ed4ee804620b4e0fe43 to your computer and use it in GitHub Desktop.
Symfony translations database clear cache method
<?php
namespace AppBundle\Translation;
use Symfony\Component\Translation\Translator as BaseTranslator;
class Translator extends BaseTranslator
{
/**
* @var TranslationRepositoryInterface
*/
private $translationRepository;
/**
* @var string
*/
private $cacheDir;
/**
* @var bool
*/
private $checkedCache = false;
public function __construct(
$locale,
MessageSelector $selector = null,
$cacheDir = null,
$debug = false,
TranslationRepositoryInterface $translationRepository
) {
parent::__construct($locale, $selector, $cacheDir, $debug);
$this->cacheDir = $cacheDir;
$this->translationRepository = $translationRepository;
}
public function getCatalogue($locale = null)
{
$this->clearCacheIfNeeded();
return parent::getCatalogue($locale);
}
private function clearCacheIfNeeded()
{
// we only need to check it once per request-response cycle.
if (false === $this->checkedCache) {
if (!file_exists($this->cacheDir)) {
return;
}
// get latest updated translation for every locale (translations grouped by locale and sorted on updatedAt)
$translations = $this->translationRepository->getLocalesForLastUpdatedAt();
foreach ($translations as $resource) {
$finder = Finder::create()
->name('catalogue.'.$this->transformLocale($resource['locale']).'*')
->in($this->cacheDir)
->files()
;
/** @var SplFileInfo $file */
foreach ($finder as $file) {
if (!file_exists($file)) {
continue;
}
// check if the cache for this locale is still fresh enough
if ($this->resourceIsFresh($resource, @$file->getMTime())) {
continue;
}
// remove the catalogue cache file, since this locale has recently updated
unlink($file);
}
}
$this->checkedCache = true;
}
}
/**
* @param array $resource
* @param $time
*
* @return bool
*/
private function resourceIsFresh(array $resource, $time)
{
if (!$resource['updatedAt'] instanceof \DateTime) {
if ($resource['createdAt']->getTimestamp() < $time) {
return true;
}
} else {
if ($resource['updatedAt']->getTimestamp() < $time) {
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment