JMSTranslationBundle提取实体静态函数中的转换键

时间:2014-04-21 07:28:10

标签: php symfony

我在Entity中有一个静态函数,它包含一个数组中的一些翻译键。

public static function aStaticFunction()
{
    return array(
        0 => 'a.translation.key',
        'another.translation.key',
    );
}

当我运行JMSTranslationBundle的extract命令时,不会提取翻译键。如何让它检测并提取它们?

1 个答案:

答案 0 :(得分:0)

JMSTranslationBundle不从实体中提取翻译密钥。所以,这就是我所做的:

创建服务并使用jms_translation.file_visitor标记:

acmecustom.translator.entity.extractor:
    class: Acme\CustomBundle\Translator\EntityExtractor
    tags:
        - { name: jms_translation.file_visitor }

提取器类(某些行/函数被截断):

<?php
namespace Acme\CustomBundle\Translator;

use JMS\TranslationBundle\Model\FileSource;
use JMS\TranslationBundle\Model\Message;
use JMS\TranslationBundle\Model\MessageCatalogue;
use JMS\TranslationBundle\Translation\Extractor\FileVisitorInterface;

class EntityExtractor implements FileVisitorInterface, \PHPParser_NodeVisitor
{
    private $traverser;
    private $catalogue;
    private $file;

    public function __construct()
    {
        $this->traverser = new \PHPParser_NodeTraverser();
        $this->traverser->addVisitor($this);
    }

    public function enterNode(\PHPParser_Node $node)
    {
        if (!$node instanceof \PHPParser_Node_Scalar_String) {
            return;
        }

        $id = $node->value;

        // ignore multiple dot without any string between them
        if (preg_match('/(\.\.|\.\.\.)/', $id)) {
            return;
        }

        // only extract dot-delimitted string such as "custom.entity.firstname"
        if (preg_match('/.*\./', $id)) {
            $domain = 'messages';
            $message = new Message($id, $domain);
            $message->addSource(new FileSource((string) $this->file, $node->getLine()));

            $this->catalogue->add($message);
        }
    }

    public function visitPhpFile(\SplFileInfo $file, MessageCatalogue $catalogue, array $ast)
    {
        $this->file = $file;
        $this->catalogue = $catalogue;

        // only extract from path/directory 'Entity'
        if ($this->file->getPathInfo()->getFilename() == 'Entity') {
            $this->traverser->traverse($ast);
        }
    }
}