php Symfony-Component-Translation-MessageCatalogue类(方法)实例源码

下面列出了php Symfony-Component-Translation-MessageCatalogue 类(方法)源码代码实例,从而了解它的用法。

作者:kyarosla    项目:RaindropTranslationBundl   
/**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // get bundle directory
     $foundBundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle'));
     $bundleTransPath = $foundBundle->getPath() . '/Resources/translations';
     $writer = $this->getContainer()->get('translation.writer');
     $supportedFormats = $writer->getFormats();
     if (!in_array($input->getOption('output-format'), $supportedFormats)) {
         $output->writeln('<error>Wrong output format</error>');
         $output->writeln('Supported formats are ' . implode(', ', $supportedFormats) . '.');
         return 1;
     }
     $this->orm = $this->getContainer()->get('doctrine.orm.default_entity_manager');
     $languages = $this->orm->getRepository('RaindropTranslationBundle:Language')->findAll();
     $tokens = $this->orm->getRepository('RaindropTranslationBundle:LanguageToken')->findAll();
     foreach ($languages as $language) {
         $output->writeln(sprintf('Generating "<info>%s</info>" translation files for "<info>%s</info>"', $language, $foundBundle->getName()));
         // create catalogue
         $catalogue = new MessageCatalogue($language);
         foreach ($tokens as $token) {
             $translation = $this->orm->getRepository('RaindropTranslationBundle:LanguageTranslation')->findOneBy(array('language' => $language, 'languageToken' => $token, 'catalogue' => $token->getCatalogue()));
             if (!empty($translation)) {
                 $content = $translation->getTranslation() != '' ? $translation->getTranslation() : null;
                 $catalogue->set($token->getToken(), $content);
             }
         }
         $writer->writeTranslations($catalogue, $input->getOption('output-format'), array('path' => $bundleTransPath));
     }
 }

作者:symstrike    项目:symfon   
/**
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     if (!stream_is_local($resource)) {
         throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
     }
     if (!file_exists($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     list($xml, $encoding) = $this->parseFile($resource);
     $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
     $catalogue = new MessageCatalogue($locale);
     foreach ($xml->xpath('//xliff:trans-unit') as $translation) {
         $attributes = $translation->attributes();
         if (!(isset($attributes['resname']) || isset($translation->source))) {
             continue;
         }
         $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
         // If the xlf file has another encoding specified, try to convert it because
         // simple_xml will always return utf-8 encoded values
         $target = $this->utf8ToCharset((string) (isset($translation->target) ? $translation->target : $source), $encoding);
         $catalogue->set((string) $source, $target, $domain);
         $metadata = array();
         if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) {
             $metadata['notes'] = $notes;
         }
         if ($translation->target->attributes()) {
             $metadata['target-attributes'] = $translation->target->attributes();
         }
         $catalogue->setMetadata((string) $source, $metadata, $domain);
     }
     if (class_exists('Symfony\\Component\\Config\\Resource\\FileResource')) {
         $catalogue->addResource(new FileResource($resource));
     }
     return $catalogue;
 }

作者:tomasstrejce    项目:Translatio   
/**
  * Extracts translation messages from a file to the catalogue.
  *
  * @param string           $file The path to look into
  * @param MessageCatalogue $catalogue The catalogue
  */
 public function extractFile($file, MessageCatalogue $catalogue)
 {
     $buffer = NULL;
     $parser = new Parser();
     $parser->shortNoEscape = TRUE;
     foreach ($tokens = $parser->parse(file_get_contents($file)) as $token) {
         if ($token->type !== $token::MACRO_TAG || !in_array($token->name, array('_', '/_'), TRUE)) {
             if ($buffer !== NULL) {
                 $buffer .= $token->text;
             }
             continue;
         }
         if ($token->name === '/_') {
             $catalogue->set(($this->prefix ? $this->prefix . '.' : '') . $buffer, $buffer);
             $buffer = NULL;
         } elseif ($token->name === '_' && empty($token->value)) {
             $buffer = '';
         } else {
             $args = new MacroTokens($token->value);
             $writer = new PhpWriter($args, $token->modifiers);
             $message = $writer->write('%node.word');
             if (in_array(substr(trim($message), 0, 1), array('"', '\''), TRUE)) {
                 $message = substr(trim($message), 1, -1);
             }
             $catalogue->set(($this->prefix ? $this->prefix . '.' : '') . $message, $message);
         }
     }
 }

作者:ChrisWesterfiel    项目:MJR.ONE-C   
/**
  * Dumps the message catalogue.
  *
  * @param MessageCatalogue $messages The message catalogue
  * @param array            $options  Options that are used by the dumper
  */
 public function dump(MessageCatalogue $messages, $options = array())
 {
     $this->loadAll = false;
     $locale = $messages->getLocale();
     try {
         foreach ($messages->getDomains() as $eachDomain) {
             foreach ($messages->all($eachDomain) as $eachKey => $eachTranslation) {
                 $queryBuilder = $this->entityManager->createQueryBuilder();
                 $queryBuilder->select('t')->from('MjrLibraryEntitiesBundle:System\\Translation', 't')->where($queryBuilder->expr()->andX($queryBuilder->expr()->eq('t.Identity', '?1'), $queryBuilder->expr()->eq('t.Locale', '?2')));
                 $query = $this->entityManager->createQuery($queryBuilder->getDQL());
                 $query->setParameters(array(1 => $eachKey, 2 => $locale));
                 $result = $query->getArrayResult();
                 if (count($result) < 1) {
                     $entry = new Translation();
                     $entry->setLocale($locale);
                     $entry->setIdentity($eachKey);
                     $entry->setTranslation($eachKey);
                     $this->entityManager->persist($entry);
                     $this->entityManager->flush();
                 }
                 unset($query, $queryBuilder, $entry, $eachKey, $eachTranslation);
             }
         }
     } catch (\Exception $ex) {
         var_dump($ex);
         die;
     }
 }

作者:saj69    项目:pip   
public function testLinearFormatCatalogue()
 {
     $catalogue = new MessageCatalogue('en');
     $catalogue->add(array('foo.bar1' => 'value1', 'foo.bar2' => 'value2'));
     $dumper = new YamlFileDumper();
     $this->assertStringEqualsFile(__DIR__ . '/../fixtures/messages_linear.yml', $dumper->formatCatalogue($catalogue, 'messages'));
 }

作者:laubosslin    项目:la   
/**
  * {@inheritDoc}
  */
 protected function format(MessageCatalogue $messages, $domain)
 {
     $dom = new \DOMDocument('1.0', 'utf-8');
     $dom->formatOutput = true;
     $xliff = $dom->appendChild($dom->createElement('xliff'));
     $xliff->setAttribute('version', '1.2');
     $xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:1.2');
     $xliffFile = $xliff->appendChild($dom->createElement('file'));
     $xliffFile->setAttribute('source-language', $messages->getLocale());
     $xliffFile->setAttribute('datatype', 'plaintext');
     $xliffFile->setAttribute('original', 'file.ext');
     $xliffBody = $xliffFile->appendChild($dom->createElement('body'));
     $id = 1;
     foreach ($messages->all($domain) as $source => $target) {
         $trans = $dom->createElement('trans-unit');
         $trans->setAttribute('id', $id);
         $s = $trans->appendChild($dom->createElement('source'));
         $s->appendChild($dom->createTextNode($source));
         $t = $trans->appendChild($dom->createElement('target'));
         $t->appendChild($dom->createTextNode($target));
         $xliffBody->appendChild($trans);
         $id++;
     }
     return $dom->saveXML();
 }

作者:ashutosh-srija    项目:findit_akene   
/**
  * @param InputInterface  $input
  * @param OutputInterface $output
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $writer = $this->getContainer()->get('translation.writer');
     if (!$this->checkParameters($input, $output, $writer)) {
         return 1;
     }
     // get bundle directory
     $foundBundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle'));
     $bundleTransPath = $foundBundle->getPath() . '/Resources/translations';
     $output->writeln(sprintf('Generating "<info>%s</info>" translation files for "<info>%s</info>"', $input->getArgument('locale'), $foundBundle->getName()));
     // create catalogue
     $catalogue = new MessageCatalogue($input->getArgument('locale'));
     $output->writeln('Parsing templates');
     $annotations = $this->getContainer()->get('oro_security.acl.annotation_provider')->getBundleAnnotations(array($foundBundle->getPath()));
     /** @var  $annotation Acl*/
     /** @var  $annotations AclAnnotationStorage*/
     foreach ($annotations->getAnnotations() as $annotation) {
         if ($label = $annotation->getLabel()) {
             $catalogue->set($label, $input->getOption('prefix') . $label);
         }
     }
     // load any existing messages from the translation files
     $output->writeln('Loading translation files');
     $loader = $this->getContainer()->get('translation.loader');
     $loader->loadMessages($bundleTransPath, $catalogue);
     // show compiled list of messages
     if ($input->getOption('dump-messages') === true) {
         $this->dumpMessages($input, $output, $catalogue);
     }
     // save the files
     if ($input->getOption('force') === true) {
         $this->saveMessages($input, $output, $catalogue, $writer, $bundleTransPath);
     }
 }

作者:sapwo    项目:portfoli   
public function testDumpWithCustomEncoding()
 {
     $catalogue = new MessageCatalogue('en');
     $catalogue->add(array('foo' => '"bar"'));
     $dumper = new JsonFileDumper();
     $this->assertStringEqualsFile(__DIR__ . '/../fixtures/resources.dump.json', $dumper->formatCatalogue($catalogue, 'messages', array('json_encoding' => JSON_HEX_QUOT)));
 }

作者:vse    项目:translat   
public function submitFormTranslate(Form $form)
 {
     $values = $form->getValues();
     //existuje preklad ?
     $translatesLocale = $this->row->related('translate_locale')->where('language_id', $this->webLanguage)->fetch();
     if ($translatesLocale) {
         if ($values['translate'] != '') {
             $translatesLocale->update(array('translate' => $values['translate']));
         } else {
             $translatesLocale->delete();
         }
     } else {
         $this->row->related('translate_locale')->insert(array('translate' => $values['translate'], 'language_id' => $this->webLanguage));
     }
     $language = $this->languages->get($this->webLanguage);
     $catalogue = new MessageCatalogue($language['translate_locale']);
     foreach ($this->model->getAll() as $translate) {
         $translatesLocale = $translate->related('translate_locale')->where('language_id', $this->webLanguage)->fetch();
         if ($translatesLocale) {
             $catalogue->set($translate['text'], $translatesLocale['translate']);
         } else {
             $catalogue->set($translate['text'], $translate['text']);
         }
     }
     $this->writer->writeTranslations($catalogue, 'neon', ['path' => $this->context->parameters['appDir'] . '/lang/']);
     $this->flashMessage($this->translator->trans('translate.translated'));
     $this->redirect('this');
 }

作者:netixpr    项目:symfon   
/**
  * {@inheritdoc}
  */
 function load($resource, $locale, $domain = 'messages')
 {
     $catalogue = new MessageCatalogue($locale);
     $catalogue->addMessages(require $resource, $domain);
     $catalogue->addResource(new FileResource($resource));
     return $catalogue;
 }

作者:kchhainaron    项目:chantuch   
/**
  * {@inheritdoc}
  */
 protected function format(MessageCatalogue $messages, $domain)
 {
     $dom = new \DOMDocument('1.0', 'utf-8');
     $dom->formatOutput = true;
     $xliff = $dom->appendChild($dom->createElement('xliff'));
     $xliff->setAttribute('version', '1.2');
     $xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:1.2');
     $xliffFile = $xliff->appendChild($dom->createElement('file'));
     $xliffFile->setAttribute('source-language', $messages->getLocale());
     $xliffFile->setAttribute('datatype', 'plaintext');
     $xliffFile->setAttribute('original', 'file.ext');
     $xliffBody = $xliffFile->appendChild($dom->createElement('body'));
     foreach ($messages->all($domain) as $source => $target) {
         $translation = $dom->createElement('trans-unit');
         $translation->setAttribute('id', md5($source));
         $translation->setAttribute('resname', $source);
         $s = $translation->appendChild($dom->createElement('source'));
         $s->appendChild($dom->createTextNode($source));
         // Does the target contain characters requiring a CDATA section?
         $text = 1 === preg_match('/[&<>]/', $target) ? $dom->createCDATASection($target) : $dom->createTextNode($target);
         $t = $translation->appendChild($dom->createElement('target'));
         $t->appendChild($text);
         $xliffBody->appendChild($translation);
     }
     return $dom->saveXML();
 }

作者:migro    项目:LiipTranslationBundl   
/**
  * Load translations and metadata of the trans-unit.
  *
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     /* @var MessageCatalogue $catalogue */
     $base_catalogue = parent::load($resource, $locale, $domain);
     $catalogue = new MessageCatalogue($locale);
     $catalogue->addCatalogue($base_catalogue);
     // Process a second pass over the file to collect metadata
     $xml = simplexml_load_file($resource);
     $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2');
     foreach ($xml->xpath('//xliff:trans-unit') as $translation) {
         // Read the attributes
         $attributes = (array) $translation->attributes();
         $attributes = $attributes['@attributes'];
         if (!(isset($attributes['resname']) || isset($translation->source)) || !isset($translation->target)) {
             continue;
         }
         $key = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
         $metadata = (array) $attributes;
         // read the notes
         if (isset($translation->note)) {
             $metadata['note'] = (string) $translation->note;
         }
         $catalogue->setMetadata((string) $key, $metadata, $domain);
     }
     return $catalogue;
 }

作者:M03    项目:PrestaSho   
private function getDatabaseCatalogue()
 {
     $databaseCatalogue = new MessageCatalogue(self::FAKE_LOCALE);
     $messages = array('baz' => 'Baz is updated !');
     $databaseCatalogue->add($messages, 'messages');
     return $databaseCatalogue;
 }

作者:Nakar    项目:symfon   
public function testTargetAttributesMetadataIsSetInFile()
    {
        $catalogue = new MessageCatalogue('en_US');
        $catalogue->add(array('foo' => 'bar'));
        $catalogue->setMetadata('foo', array('target-attributes' => array('state' => 'needs-translation')));
        $tempDir = sys_get_temp_dir();
        $dumper = new XliffFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir, 'default_locale' => 'fr_FR'));
        $content = <<<EOT
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
  <file source-language="fr-FR" target-language="en-US" datatype="plaintext" original="file.ext">
    <body>
      <trans-unit id="acbd18db4cc2f85cedef654fccc4a4d8" resname="foo">
        <source>foo</source>
        <target state="needs-translation">bar</target>
      </trans-unit>
    </body>
  </file>
</xliff>

EOT;
        $this->assertEquals($content, file_get_contents($tempDir . '/messages.en_US.xlf'));
        unlink($tempDir . '/messages.en_US.xlf');
    }

作者:EnmanuelCod    项目:backend-larave   
/**
  * {@inheritdoc}
  */
 protected function format(MessageCatalogue $messages, $domain)
 {
     if (!class_exists('Symfony\\Component\\Yaml\\Yaml')) {
         throw new \LogicException('Dumping translations in the YAML format requires the Symfony Yaml component.');
     }
     return Yaml::dump($messages->all($domain));
 }

作者:scottstuf    项目:GCProtractorJ   
/**
  * Loads a locale.
  *
  * @param mixed $resource A resource
  * @param string $locale   A locale
  * @param string $domain   The domain
  *
  * @return MessageCatalogue A MessageCatalogue instance
  *
  * @throws NotFoundResourceException when the resource cannot be found
  * @throws InvalidResourceException  when the resource cannot be loaded
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     $translations = $this->translationRepo->kvByLocaleAndDomain($locale, $domain);
     $catalogue = new MessageCatalogue($locale);
     $catalogue->add($translations, $domain);
     return $catalogue;
 }

作者:vse    项目:translat   
/**
  * Extracts translation messages from a file to the catalogue.
  *
  * @param string           $file The path to look into
  * @param MessageCatalogue $catalogue The catalogue
  */
 public function extractFile($file, MessageCatalogue $catalogue)
 {
     $pInfo = pathinfo($file);
     $tokens = token_get_all(file_get_contents($file));
     $data = array();
     foreach ($tokens as $c) {
         if (is_array($c)) {
             if ($c[0] != T_STRING && $c[0] != T_CONSTANT_ENCAPSED_STRING) {
                 continue;
             }
             if ($c[0] == T_STRING && in_array($c[1], $this->keywords)) {
                 $next = true;
                 continue;
             }
             if ($c[0] == T_CONSTANT_ENCAPSED_STRING && $next == true) {
                 $data[substr($c[1], 1, -1)][] = $pInfo['basename'] . ':' . $c[2];
                 $next = false;
             }
         } else {
             if ($c == ')') {
                 $next = false;
             }
         }
     }
     foreach ($data as $d => $value) {
         $catalogue->set(($this->prefix ? $this->prefix . '.' : '') . $d, $d);
     }
 }

作者:EnmanuelCod    项目:backend-larave   
/**
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     if (!stream_is_local($resource)) {
         throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
     }
     if (!file_exists($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     try {
         $dom = XmlUtils::loadFile($resource);
     } catch (\InvalidArgumentException $e) {
         throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e);
     }
     $internalErrors = libxml_use_internal_errors(true);
     libxml_clear_errors();
     $xpath = new \DOMXPath($dom);
     $nodes = $xpath->evaluate('//TS/context/name[text()="' . $domain . '"]');
     $catalogue = new MessageCatalogue($locale);
     if ($nodes->length == 1) {
         $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
         foreach ($translations as $translation) {
             $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
             if (!empty($translationValue)) {
                 $catalogue->set((string) $translation->getElementsByTagName('source')->item(0)->nodeValue, $translationValue, $domain);
             }
             $translation = $translation->nextSibling;
         }
         $catalogue->addResource(new FileResource($resource));
     }
     libxml_use_internal_errors($internalErrors);
     return $catalogue;
 }

作者:dev-la    项目:htdoc   
/**
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     if (!stream_is_local($resource)) {
         throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
     }
     if (!file_exists($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     $dom = new \DOMDocument();
     $current = libxml_use_internal_errors(true);
     if (!@$dom->load($resource, defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0)) {
         throw new InvalidResourceException(implode("\n", $this->getXmlErrors()));
     }
     $xpath = new \DOMXPath($dom);
     $nodes = $xpath->evaluate('//TS/context/name[text()="' . $domain . '"]');
     $catalogue = new MessageCatalogue($locale);
     if ($nodes->length == 1) {
         $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message');
         foreach ($translations as $translation) {
             $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue;
             if (!empty($translationValue)) {
                 $catalogue->set((string) $translation->getElementsByTagName('source')->item(0)->nodeValue, $translationValue, $domain);
             }
             $translation = $translation->nextSibling;
         }
         $catalogue->addResource(new FileResource($resource));
     }
     libxml_use_internal_errors($current);
     return $catalogue;
 }

作者:keek    项目:framewor   
/**
  * {@inheritDoc}
  * @see \Symfony\Component\Translation\Loader\LoaderInterface::load()
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     $repo = $this->service->getResourceRepository();
     if (!$repo->contains($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     // find file in puli repo
     $file = $repo->get($resource);
     $json = $file->getBody();
     $data = Json::decode($json);
     $messages = [];
     // flatten plural strings
     foreach ($data as $key => $value) {
         if (is_array($value)) {
             $vals = [];
             foreach ($value as $k => $v) {
                 $vals[] = sprintf('%s: %s', $k, $v);
             }
             $val = implode('|', $vals);
         } else {
             $val = $value;
         }
         $messages[$key] = str_replace(['{{', '}}'], '%', $val);
     }
     // put them into message catalog
     $catalogue = new MessageCatalogue($locale);
     $catalogue->add($messages, $domain);
     return $catalogue;
 }


问题


面经


文章

微信
公众号

扫码关注公众号