Skip to content

[2.8][Translation] added message cache. #14526

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

Closed
wants to merge 1 commit into from
Closed
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 @@ -582,6 +582,7 @@ private function addTranslatorSection(ArrayNodeDefinition $rootNode)
->defaultValue(array('en'))
->end()
->booleanNode('logging')->defaultValue($this->debug)->end()
->scalarNode('cache')->defaultValue('translation.cache.default')->end()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,14 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder

$container->setParameter('translator.logging', $config['logging']);

if (isset($config['cache'])) {
$container->setParameter(
'translator.cache.prefix',
'translator_'.hash('sha256', $container->getParameter('kernel.root_dir'))
);
$container->setAlias('translation.cache', $config['cache']);
}

// Discover translation directories
$dirs = array();
if (class_exists('Symfony\Component\Validator\Validation')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="fallback" type="xsd:string" />
<xsd:attribute name="logging" type="xsd:boolean" />
<xsd:attribute name="cache" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="validation">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<parameter key="translation.loader.class">Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader</parameter>
<parameter key="translation.extractor.class">Symfony\Component\Translation\Extractor\ChainExtractor</parameter>
<parameter key="translation.writer.class">Symfony\Component\Translation\Writer\TranslationWriter</parameter>
<parameter key="translator.cache.prefix" />
</parameters>

<services>
Expand All @@ -44,7 +45,7 @@
<argument key="cache_dir">%kernel.cache_dir%/translations</argument>
<argument key="debug">%kernel.debug%</argument>
</argument>
<argument type="collection" /> <!-- translation resources -->
<argument type="service" id="translation.cache" on-invalid="null" />
</service>

<service id="translator.logging" class="Symfony\Component\Translation\LoggingTranslator" public="false">
Expand Down Expand Up @@ -157,5 +158,11 @@
<argument type="service" id="translator" />
<tag name="kernel.cache_warmer" />
</service>

<!-- Cache -->
<service id="translation.cache.default" class="Symfony\Component\Translation\MessageCache" public="false">
<argument>%kernel.cache_dir%/translations</argument> <!-- cache_dir -->
<argument>%kernel.debug%</argument> <!-- debug -->
</service>
</services>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ protected static function getBundleDefaultConfig()
'enabled' => false,
'fallbacks' => array('en'),
'logging' => true,
'cache' => 'translation.cache.default',
),
'validation' => array(
'enabled' => false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ public function testTranslator()

$calls = $container->getDefinition('translator.default')->getMethodCalls();
$this->assertEquals(array('fr'), $calls[0][1][0]);
$this->assertContains('translator_', $container->getParameter('translator.cache.prefix'));
}

public function testTranslatorMultipleFallbacks()
Expand Down
15 changes: 9 additions & 6 deletions src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Translation\Translator as BaseTranslator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Translation\MessageCacheInterface;

/**
* Translator.
Expand Down Expand Up @@ -46,14 +47,15 @@ class Translator extends BaseTranslator implements WarmableInterface
* * debug: Whether to enable debugging or not (false by default)
* * resource_files: List of translation resources available grouped by locale.
*
* @param ContainerInterface $container A ContainerInterface instance
* @param MessageSelector $selector The message selector for pluralization
* @param array $loaderIds An array of loader Ids
* @param array $options An array of options
* @param ContainerInterface $container A ContainerInterface instance
* @param MessageSelector $selector The message selector for pluralization
* @param array $loaderIds An array of loader Ids
* @param array $options An array of options
* @param MessageCacheInterface $cache The message cache
*
* @throws \InvalidArgumentException
*/
public function __construct(ContainerInterface $container, MessageSelector $selector, $loaderIds = array(), array $options = array())
public function __construct(ContainerInterface $container, MessageSelector $selector, $loaderIds = array(), array $options = array(), MessageCacheInterface $cache = null)
{
$this->container = $container;
$this->loaderIds = $loaderIds;
Expand All @@ -69,7 +71,8 @@ public function __construct(ContainerInterface $container, MessageSelector $sele
$this->loadResources();
}

parent::__construct($container->getParameter('kernel.default_locale'), $selector, $this->options['cache_dir'], $this->options['debug']);
$cache = $cache ?: $this->options['cache_dir'];
parent::__construct($container->getParameter('kernel.default_locale'), $selector, $cache, $this->options['debug']);
}

/**
Expand Down
152 changes: 152 additions & 0 deletions src/Symfony/Component/Translation/MessageCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Translation;

use Symfony\Component\Config\ConfigCacheInterface;
use Symfony\Component\Config\ConfigCacheFactoryInterface;
use Symfony\Component\Config\ConfigCacheFactory;

/**
* @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
*/
class MessageCache implements MessageCacheInterface
{
/**
* @var string
*/
private $cacheDir;

/**
* @var bool
*/
private $debug;

/**
* @var ConfigCacheFactoryInterface
*/
private $configCacheFactory;

/**
* @param string $cacheDir
* @param bool $debug
* @param ConfigCacheFactoryInterface $configCacheFactory
*/
public function __construct($cacheDir, $debug = false, ConfigCacheFactoryInterface $configCacheFactory = null)
{
$this->cacheDir = $cacheDir;
$this->debug = $debug;

if (null === $configCacheFactory) {
$configCacheFactory = new ConfigCacheFactory($debug);
}

$this->configCacheFactory = $configCacheFactory;
}

/**
* Sets the ConfigCache factory to use.
*
* @param ConfigCacheFactoryInterface $configCacheFactory
*/
public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory)
{
trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);

$this->configCacheFactory = $configCacheFactory;
}

/**
* {@inheritdoc}
*/
public function cache($locale, array $options = array())
{
$defaultOptions = array(
'resources' => array(),
'fallback_locales' => array(),
'initialize_catalogue' => function ($locale) {
return new MessageCatalogue($locale);
},
);

$options = array_merge($defaultOptions, $options);
$self = $this; // required for PHP 5.3 where "$this" cannot be used in anonymous functions. Change in Symfony 3.0.
$cache = $this->configCacheFactory->cache($this->getCatalogueCachePath($locale, $options),
function (ConfigCacheInterface $cache) use ($self, $locale, $options) {
$self->dumpCatalogue($locale, $options, $cache);
}
);

/* Read catalogue from cache. */
return include $cache->getPath();
}

/**
* This method is public because it needs to be callable from a closure in PHP 5.3. It should be made protected (or even private, if possible) in 3.0.
*
* @internal
*/
public function dumpCatalogue($locale, $options, ConfigCacheInterface $cache)
{
$catalogue = $options['initialize_catalogue']($locale);
$fallbackContent = $this->getFallbackContent($catalogue, $options);
$content = sprintf(<<<EOF
<?php
use Symfony\Component\Translation\MessageCatalogue;
\$catalogue = new MessageCatalogue('%s', %s);
%s
return \$catalogue;
EOF
,
$locale,
var_export($catalogue->all(), true),
$fallbackContent
);
$cache->write($content, $catalogue->getResources());
}
private function getFallbackContent(MessageCatalogue $catalogue, $options)
{
$fallbackContent = '';
$current = '';
$replacementPattern = '/[^a-z0-9_]/i';
$fallbackCatalogue = $catalogue->getFallbackCatalogue();
while ($fallbackCatalogue) {
$fallback = $fallbackCatalogue->getLocale();
$fallbackSuffix = ucfirst(preg_replace($replacementPattern, '_', $fallback));
$currentSuffix = ucfirst(preg_replace($replacementPattern, '_', $current));
$fallbackContent .= sprintf(<<<EOF
\$catalogue%s = new MessageCatalogue('%s', %s);
\$catalogue%s->addFallbackCatalogue(\$catalogue%s);
EOF
,
$fallbackSuffix,
$fallback,
var_export($fallbackCatalogue->all(), true),
$currentSuffix,
$fallbackSuffix
);
$current = $fallbackCatalogue->getLocale();
$fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue();
}

return $fallbackContent;
}

private function getCatalogueCachePath($locale, $options)
{
$catalogueHash = sha1(serialize(array(
'resources' => $options['resources'],
'fallback_locales' => $options['fallback_locales'],
)));

return $this->cacheDir.'/catalogue.'.$locale.'.'.$catalogueHash.'.php';
}
}
28 changes: 28 additions & 0 deletions src/Symfony/Component/Translation/MessageCacheInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Translation;

/**
* @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
*/
interface MessageCacheInterface
{
/**
* Loads a catalogue from cache and (re-)initializes it if necessary.
*
* @param string $locale
* @param array $options
*
* @return MessageCatalogueInterface A MessageCatalogue instance
*/
public function cache($locale, array $options = array());
}
Loading