symfony_translation-1.0.0-alpha1/src/SymfonyTranslation.php
src/SymfonyTranslation.php
<?php
namespace Drupal\symfony_translation;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\StringTranslation\Translator\TranslatorInterface;
use Drupal\symfony_translation\Translator\Translator;
use Drupal\symfony_translation\Translator\TranslatorFactory;
use Symfony\Contracts\Translation\TranslatorInterface as SymfonyTranslatorInterface;
/**
* String translator using the Symfony Translation component.
*/
class SymfonyTranslation implements TranslatorInterface {
use DependencySerializationTrait;
protected CacheBackendInterface $cache;
protected SymfonyTranslatorInterface $translator;
/**
* Constructs a SymfonyTranslation object.
*
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* The cache backend.
* @param \Symfony\Contracts\Translation\TranslatorInterface $translator
* The translator.
*/
public function __construct(
CacheBackendInterface $cache,
SymfonyTranslatorInterface $translator,
) {
$this->cache = $cache;
$this->translator = $translator;
}
/**
* {@inheritdoc}
*/
public function getStringTranslation($langcode, $string, $context) {
$translation = $this->translator->trans($string, [], $context ?: NULL, $langcode);
if ($translation === $string) {
return FALSE;
}
return $translation;
}
/**
* {@inheritdoc}
*/
public function reset() {
// Delete cached translation file paths.
$this->cache->delete('symfony_translation.translation_files');
// Delete cached catalogues.
$cacheDir = static::getCacheDirectory();
if (!file_exists($cacheDir)) {
return;
}
$di = new \RecursiveDirectoryIterator($cacheDir, \FilesystemIterator::SKIP_DOTS);
$ri = new \RecursiveIteratorIterator($di, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ri as $file) {
$file->isDir() ? rmdir($file) : unlink($file);
}
}
/**
* Gets the path to the directory in which catalogues will be cached.
*
* @return string
* The path to the directory.
*/
public static function getCacheDirectory(): string {
// Not using the public stream wrapper to prevent 'stream_set_option() not supported' warnings.
return sprintf('%s/%s/symfony_translation', DRUPAL_ROOT, PublicStream::basePath());
}
}
