/**
  * {@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));
     }
 }
Пример #2
0
 /**
  * {@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;
 }
Пример #3
0
 /**
  * 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);
         }
     }
 }
Пример #4
0
 /**
  * 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;
     }
 }
Пример #5
0
 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'));
 }
Пример #6
0
 /**
  * {@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();
 }
 /**
  * @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);
     }
 }
Пример #8
0
 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)));
 }
Пример #9
0
 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');
 }
Пример #10
0
 /**
  * {@inheritdoc}
  */
 function load($resource, $locale, $domain = 'messages')
 {
     $catalogue = new MessageCatalogue($locale);
     $catalogue->addMessages(require $resource, $domain);
     $catalogue->addResource(new FileResource($resource));
     return $catalogue;
 }
Пример #11
0
 /**
  * {@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();
 }
 /**
  * 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;
 }
 private function getDatabaseCatalogue()
 {
     $databaseCatalogue = new MessageCatalogue(self::FAKE_LOCALE);
     $messages = array('baz' => 'Baz is updated !');
     $databaseCatalogue->add($messages, 'messages');
     return $databaseCatalogue;
 }
Пример #14
0
    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');
    }
 /**
  * {@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));
 }
 /**
  * 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;
 }
Пример #17
0
 /**
  * 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);
     }
 }
Пример #18
0
 /**
  * {@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;
 }
Пример #19
0
 /**
  * {@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;
 }
Пример #20
0
 /**
  * {@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;
 }
Пример #21
0
    /**
     * 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')
    {
        if ($this->loadAll !== true) {
            return new MessageCatalogue($locale);
        }
        $dql = <<<'DQL'
                SELECT
                  t
                FROM
                  MjrLibraryEntitiesBundle:System\Translation t
              WHERE
                  t.Locale = :locale
              ORDER BY t.Id ASC
DQL;
        $query = $this->entityManager->createQuery($dql);
        $query->setParameter(':locale', $locale);
        /** @var Translation[] $results */
        $results = $query->getResult();
        $catalogue = new MessageCatalogue($locale);
        if (count($results) > 0) {
            foreach ($results as $result) {
                $catalogue->set($result->getIdentity(), $result->getTranslation(), $domain);
            }
        }
        return $catalogue;
    }
Пример #22
0
 /**
  *
  * {@inheritdoc}
  *
  */
 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 (!is_dir($resource)) {
         throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
     }
     try {
         $rb = new \ResourceBundle($locale, $resource);
     } catch (\Exception $e) {
         // HHVM compatibility: constructor throws on invalid resource
         $rb = null;
     }
     if (!$rb) {
         throw new InvalidResourceException(sprintf('Cannot load resource "%s"', $resource));
     } elseif (intl_is_failure($rb->getErrorCode())) {
         throw new InvalidResourceException($rb->getErrorMessage(), $rb->getErrorCode());
     }
     $messages = $this->flatten($rb);
     $catalogue = new MessageCatalogue($locale);
     $catalogue->add($messages, $domain);
     if (class_exists('Symfony\\Component\\Config\\Resource\\DirectoryResource')) {
         $catalogue->addResource(new DirectoryResource($resource));
     }
     return $catalogue;
 }
Пример #23
0
 /**
  * {@inheritDoc}
  */
 protected function format(MessageCatalogue $messages, $domain)
 {
     $m = $messages->all($domain);
     if ($this->nestLevel > 0) {
         // build a message tree from the message list, with a max depth
         // of $this->nestLevel
         $tree = array();
         foreach ($m as $key => $message) {
             // dots are ignored at the beginning and at the end of a key
             $key = trim($key, "\t .");
             if (strlen($key) > 0) {
                 $codes = explode('.', $key, $this->nestLevel + 1);
                 $node =& $tree;
                 foreach ($codes as $code) {
                     if (strlen($code) > 0) {
                         if (!isset($node)) {
                             $node = array();
                         }
                         $node =& $node[$code];
                     }
                 }
                 $node = $message;
             }
         }
         return Yaml::dump($tree, $this->nestLevel + 1);
         // second parameter at 1 outputs normal line-by-line catalogue
     } else {
         return Yaml::dump($m, 1);
     }
 }
Пример #24
0
 public function testFormatCatalogue()
 {
     $catalogue = new MessageCatalogue('en');
     $catalogue->add(array('foo' => 'bar'), 'resources');
     $dumper = new QtFileDumper();
     $this->assertStringEqualsFile(__DIR__ . '/../fixtures/resources.ts', $dumper->formatCatalogue($catalogue, 'resources'));
 }
Пример #25
0
 /**
  * {@inheritdoc}
  *
  * @api
  */
 public function load($resource, $locale, $domain = 'messages')
 {
     $this->flatten($resource);
     $catalogue = new MessageCatalogue($locale);
     $catalogue->add($resource, $domain);
     return $catalogue;
 }
Пример #26
0
 /**
  * {@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)) || !isset($translation->target)) {
             continue;
         }
         $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source;
         $target = (string) $translation->target;
         // If the xlf file has another encoding specified, try to convert it because
         // simple_xml will always return utf-8 encoded values
         if ('UTF-8' !== $encoding && !empty($encoding)) {
             if (function_exists('mb_convert_encoding')) {
                 $target = mb_convert_encoding($target, $encoding, 'UTF-8');
             } elseif (function_exists('iconv')) {
                 $target = iconv('UTF-8', $encoding, $target);
             } else {
                 throw new \RuntimeException('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
             }
         }
         $catalogue->set((string) $source, $target, $domain);
     }
     $catalogue->addResource(new FileResource($resource));
     return $catalogue;
 }
Пример #27
0
 public function testDumpWithCustomEncoding()
 {
     $catalogue = new MessageCatalogue('en');
     $catalogue->add(array('foo' => '"bar"'));
     $dumper = new JsonFileDumper();
     $dumper->dump($catalogue, array('path' => $this->tempDir, 'json_encoding' => JSON_HEX_QUOT));
     $this->assertEquals(file_get_contents(__DIR__ . '/../fixtures/resources.dump.json'), file_get_contents($this->tempDir . '/messages.en.json'));
 }
Пример #28
0
 public function testFormatCatalogueWithTargetAttributesMetadata()
 {
     $catalogue = new MessageCatalogue('en_US');
     $catalogue->add(array('foo' => 'bar'));
     $catalogue->setMetadata('foo', array('target-attributes' => array('state' => 'needs-translation')));
     $dumper = new XliffFileDumper();
     $this->assertStringEqualsFile(__DIR__ . '/../fixtures/resources-target-attributes.xlf', $dumper->formatCatalogue($catalogue, 'messages', array('default_locale' => 'fr_FR')));
 }
 public function load($resource, $locale, $domain = 'messages')
 {
     $catalogue = new MessageCatalogue($locale);
     if ($resource instanceof \Closure) {
         $catalogue->add($resource());
     }
     return $catalogue;
 }
Пример #30
0
 protected function getCatalogue($locale, $messages)
 {
     $catalogue = new MessageCatalogue($locale);
     foreach ($messages as $key => $translation) {
         $catalogue->set($key, $translation);
     }
     return $catalogue;
 }