Skip to content

Improve Translator caching #28937

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,7 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
// Discover translation directories
$dirs = [];
$transPaths = [];
$nonExistingDirs = [];
if (class_exists('Symfony\Component\Validator\Validation')) {
$r = new \ReflectionClass('Symfony\Component\Validator\Validation');

Expand All @@ -1093,18 +1094,21 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
$defaultDir = $container->getParameterBag()->resolveValue($config['default_path']);
$rootDir = $container->getParameter('kernel.root_dir');
foreach ($container->getParameter('kernel.bundles_metadata') as $name => $bundle) {
if ($container->fileExists($dir = $bundle['path'].'/Resources/translations')) {
if (\is_dir($dir = $bundle['path'].'/Resources/translations')) {
$dirs[] = $dir;
} else {
$nonExistingDirs[] = $dir;
}
if ($container->fileExists($dir = $rootDir.sprintf('/Resources/%s/translations', $name))) {
if (\is_dir($dir = $rootDir.sprintf('/Resources/%s/translations', $name))) {
@trigger_error(sprintf('Translations directory "%s" is deprecated since Symfony 4.2, use "%s" instead.', $dir, $defaultDir), E_USER_DEPRECATED);

$dirs[] = $dir;
} else {
$nonExistingDirs[] = $dir;
}
}

foreach ($config['paths'] as $dir) {
if ($container->fileExists($dir)) {
if (\is_dir($dir)) {
$dirs[] = $transPaths[] = $dir;
} else {
throw new \UnexpectedValueException(sprintf('%s defined in translator.paths does not exist or is not a directory', $dir));
Expand All @@ -1119,15 +1123,20 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder
$container->getDefinition('console.command.translation_update')->replaceArgument(6, $transPaths);
}

if ($container->fileExists($defaultDir)) {
if (\is_dir($defaultDir)) {
$dirs[] = $defaultDir;
} else {
$nonExistingDirs[] = $defaultDir;
}
if ($container->fileExists($dir = $rootDir.'/Resources/translations')) {

if (\is_dir($dir = $rootDir.'/Resources/translations')) {
if ($dir !== $defaultDir) {
@trigger_error(sprintf('Translations directory "%s" is deprecated since Symfony 4.2, use "%s" instead.', $dir, $defaultDir), E_USER_DEPRECATED);
}

$dirs[] = $dir;
} else {
$nonExistingDirs[] = $dir;
}

// Register translation resources
Expand All @@ -1154,7 +1163,10 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder

$options = array_merge(
$translator->getArgument(4),
['resource_files' => $files]
[
'resource_files' => $files,
'scanned_directories' => \array_merge($dirs, $nonExistingDirs),
]
);

$translator->replaceArgument(4, $options);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\ProxyAdapter;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Config\Resource\FileExistenceResource;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ResolveInstanceofConditionalsPass;
Expand Down Expand Up @@ -800,6 +802,26 @@ public function testTranslator()

$calls = $container->getDefinition('translator.default')->getMethodCalls();
$this->assertEquals(['fr'], $calls[1][1][0]);

$nonExistingDirectories = array_filter(
$options['scanned_directories'],
function ($directory) {
return !file_exists($directory);
}
);

$this->assertNotEmpty($nonExistingDirectories, 'FrameworkBundle should pass non existing directories to Translator');

$resources = $container->getResources();
foreach ($resources as $resource) {
if ($resource instanceof DirectoryResource) {
$this->assertNotContains('translations', $resource->getResource());
}

if ($resource instanceof FileExistenceResource) {
$this->assertNotContains('translations', $resource->getResource());
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Translation\Translator;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Config\Resource\FileExistenceResource;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Translation\Formatter\MessageFormatter;
use Symfony\Component\Translation\MessageCatalogue;
Expand Down Expand Up @@ -223,6 +225,29 @@ public function getDebugModeAndCacheDirCombinations()
];
}

public function testCatalogResourcesAreAddedForScannedDirectories()
{
$loader = new \Symfony\Component\Translation\Loader\YamlFileLoader();
$resourceFiles = [
'fr' => [
__DIR__.'/../Fixtures/Resources/translations/messages.fr.yml',
],
];

/** @var Translator $translator */
$translator = $this->getTranslator($loader, [
'resource_files' => $resourceFiles,
'scanned_directories' => [__DIR__, '/tmp/I/sure/hope/this/does/not/exist'],
], 'yml');

$catalogue = $translator->getCatalogue('fr');

$resources = $catalogue->getResources();

$this->assertEquals(new DirectoryResource(__DIR__), $resources[1]);
$this->assertEquals(new FileExistenceResource('/tmp/I/sure/hope/this/does/not/exist'), $resources[2]);
}

protected function getCatalogue($locale, $messages, $resources = [])
{
$catalogue = new MessageCatalogue($locale);
Expand Down
19 changes: 19 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
namespace Symfony\Bundle\FrameworkBundle\Translation;

use Psr\Container\ContainerInterface;
use Symfony\Component\Config\Resource\DirectoryResource;
use Symfony\Component\Config\Resource\FileExistenceResource;
use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
use Symfony\Component\Translation\Exception\InvalidArgumentException;
use Symfony\Component\Translation\Formatter\MessageFormatterInterface;
Expand All @@ -31,6 +33,7 @@ class Translator extends BaseTranslator implements WarmableInterface
'cache_dir' => null,
'debug' => false,
'resource_files' => [],
'scanned_directories' => [],
];

/**
Expand All @@ -48,6 +51,11 @@ class Translator extends BaseTranslator implements WarmableInterface

private $resourceFiles;

/**
* @var string[]
*/
private $scannedDirectories;

/**
* Constructor.
*
Expand Down Expand Up @@ -78,6 +86,7 @@ public function __construct(ContainerInterface $container, MessageFormatterInter
$this->options = array_merge($this->options, $options);
$this->resourceLocales = array_keys($this->options['resource_files']);
$this->resourceFiles = $this->options['resource_files'];
$this->scannedDirectories = $this->options['scanned_directories'];

parent::__construct($defaultLocale, $formatter, $this->options['cache_dir'], $this->options['debug']);
}
Expand Down Expand Up @@ -120,6 +129,16 @@ protected function initializeCatalogue($locale)
parent::initializeCatalogue($locale);
}

protected function doLoadCatalogue($locale): void
{
parent::doLoadCatalogue($locale);

foreach ($this->scannedDirectories as $directory) {
$resourceClass = file_exists($directory) ? DirectoryResource::class : FileExistenceResource::class;
$this->catalogues[$locale]->addResource(new $resourceClass($directory));
}
}

protected function initialize()
{
if ($this->resourceFiles) {
Expand Down
5 changes: 4 additions & 1 deletion src/Symfony/Component/Translation/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,10 @@ private function getCatalogueCachePath($locale)
return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('sha256', serialize($this->fallbackLocales), true)), 0, 7), '/', '_').'.php';
}

private function doLoadCatalogue($locale): void
/**
* @internal
*/
protected function doLoadCatalogue($locale): void
{
$this->catalogues[$locale] = new MessageCatalogue($locale);

Expand Down