/** * 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; } }
/** * {@inheritDoc} */ public function dump(MessageCatalogue $messages, $options = array()) { if (!array_key_exists('path', $options)) { throw new \InvalidArgumentException('The file dumper needs a path option.'); } $path = $options['path']; $bundleName = isset($options['bundleName']) ? $options['bundleName'] : ''; $generatedFiles = array(); // save a file for each domain foreach ($messages->getDomains() as $domain) { $fileName = !empty($bundleName) ? sprintf('%s.%s.%s.xlsx', $bundleName, $domain, $messages->getLocale()) : sprintf('%s.%s.xlsx', $domain, $messages->getLocale()); // create the exporter file $exporter = new ExcelExporter($path); // create the header row $row = array('key', $messages->getLocale()); $exporter->writeRow($row); // format the data and write to file $data = $this->format($messages, $domain); foreach ($data as $row) { $exporter->writeRow($row); } $generatedFiles[] = $exporter->generateFile($fileName); } return $generatedFiles; }
/** * {@inheritDoc} */ public function dump(MessageCatalogue $messages, $options = array()) { if (!array_key_exists('path', $options)) { throw new \InvalidArgumentException('The file dumper need a path options.'); } // save a file for each domain foreach ($messages->getDomains() as $domain) { $file = $domain.'.'.$messages->getLocale().'.'.$this->getExtension(); // backup if (file_exists($options['path'].$file)) { copy($options['path'].$file, $options['path'].'/'.$file.'~'); } // save file file_put_contents($options['path'].'/'.$file, $this->format($messages, $domain)); } }
/** * {@inheritDoc} */ public function dump(MessageCatalogue $messages, $options = array()) { if (!array_key_exists('path', $options)) { throw new \InvalidArgumentException('The file dumper needs a path option.'); } // save a file for each domain $generatedFiles = array(); $bundleName = isset($options['bundleName']) ? $options['bundleName'] : ''; foreach ($messages->getDomains() as $domain) { $fileName = !empty($bundleName) ? sprintf('%s.%s.%s.%s', $bundleName, $domain, $messages->getLocale(), $this->getExtension()) : sprintf('%s.%s.%s', $domain, $messages->getLocale(), $this->getExtension()); $fullpath = sprintf('%s/%s', $options['path'], $fileName); // save file file_put_contents($fullpath, $this->format($messages, $domain)); $generatedFiles[] = $fullpath; } return $generatedFiles; }
/** * {@inheritDoc} */ public function dump(MessageCatalogue $messages, $options = array()) { if (!array_key_exists('path', $options)) { throw new \InvalidArgumentException('The file dumper needs a path option.'); } // save a file for each domain foreach ($messages->getDomains() as $domain) { // backup $fullpath = $options['path'] . '/' . $this->getRelativePath($domain, $messages->getLocale()); if (file_exists($fullpath)) { copy($fullpath, $fullpath . '~'); } else { $directory = dirname($fullpath); if (!file_exists($directory) && !@mkdir($directory, 0777, true)) { throw new \RuntimeException(sprintf('Unable to create directory "%s".', $directory)); } } // save file file_put_contents($fullpath, $this->format($messages, $domain)); } }
/** * {@inheritdoc} */ public function dump(MessageCatalogue $messages, $options = array()) { $connection = \Propel::getConnection($this->query->getDbName()); $connection->beginTransaction(); $now = new \DateTime(); $locale = $messages->getLocale(); foreach ($messages->getDomains() as $eachDomain) { foreach ($messages->all($eachDomain) as $eachKey => $eachTranslation) { $query = clone $this->query; $query->filterBy($this->getColumnPhpname('locale'), $locale)->filterBy($this->getColumnPhpname('domain'), $eachDomain)->filterBy($this->getColumnPhpname('key'), $eachKey); $translation = $query->findOneOrCreate($connection); $translation->setByName($this->getColumnPhpname('translation'), (string) $eachTranslation); $translation->setByName($this->getColumnPhpname('updated_at'), $now); $translation->save($connection); } } if (!$connection->commit()) { $connection->rollBack(); throw new \RuntimeException(sprintf('An error occurred while committing the transaction. [%s: %s]', $connection->errorCode(), $connection->errorInfo())); } }
/** * {@inheritdoc} */ public function dump(MessageCatalogue $messages, $options = array()) { if (!array_key_exists('path', $options)) { throw new \InvalidArgumentException('The file dumper needs a path option.'); } // save a file for each domain foreach ($messages->getDomains() as $domain) { // backup $fullpath = $options['path'] . '/' . $this->getRelativePath($domain, $messages->getLocale()); if (file_exists($fullpath)) { if ($this->backup) { @trigger_error('Creating a backup while dumping a message catalogue is deprecated since version 3.1 and will be removed in 4.0. Use TranslationWriter::disableBackup() to disable the backup.', E_USER_DEPRECATED); copy($fullpath, $fullpath . '~'); } } else { $directory = dirname($fullpath); if (!file_exists($directory) && !@mkdir($directory, 0777, true)) { throw new \RuntimeException(sprintf('Unable to create directory "%s".', $directory)); } } // save file file_put_contents($fullpath, $this->formatCatalogue($messages, $domain, $options)); } }
public function testGetDomains() { $catalogue = new MessageCatalogue('en', array('domain1' => array(), 'domain2' => array())); $this->assertEquals(array('domain1', 'domain2'), $catalogue->getDomains()); }
/** * @see Command */ protected function execute(InputInterface $input, OutputInterface $output) { $twig = $this->getContainer()->get('twig'); $this->prefix = $input->getOption('prefix'); if ($input->getOption('force') !== true && $input->getOption('dump-messages') !== true) { $output->writeln('You must choose one of --force or --dump-messages'); } else { // 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())); $output->writeln('Parsing files.'); // load any messages from templates $this->messages = new \Symfony\Component\Translation\MessageCatalogue($input->getArgument('locale')); $finder = new Finder(); $files = $finder->files()->name('*.html.twig')->in($foundBundle->getPath() . '/Resources/views/'); foreach ($files as $file) { $output->writeln(sprintf(' > parsing template <comment>%s</comment>', $file->getPathname())); $tree = $twig->parse($twig->tokenize(file_get_contents($file->getPathname()))); $this->_crawlNode($tree); } // load any existing yml translation files $finder = new Finder(); $files = $finder->files()->name('*.' . $input->getArgument('locale') . '.yml')->in($bundleTransPath); foreach ($files as $file) { $output->writeln(sprintf(' > parsing translation <comment>%s</comment>', $file->getPathname())); $domain = substr($file->getFileName(), 0, strrpos($file->getFileName(), $input->getArgument('locale') . '.yml') - 1); $yml_loader = new \Symfony\Component\Translation\Loader\YamlFileLoader(); $this->messages->addCatalogue($yml_loader->load($file->getPathname(), $input->getArgument('locale'), $domain)); } // load any existing xliff translation files $finder = new Finder(); $files = $finder->files()->name('*.' . $input->getArgument('locale') . '.xliff')->in($bundleTransPath); foreach ($files as $file) { $output->writeln(sprintf(' > parsing translation <comment>%s</comment>', $file->getPathname())); $domain = substr($file->getFileName(), 0, strrpos($file->getFileName(), $input->getArgument('locale') . '.xliff') - 1); $loader = new \Symfony\Component\Translation\Loader\XliffFileLoader(); $this->messages->addCatalogue($loader->load($file->getPathname(), $input->getArgument('locale'), $domain)); } // load any existing php translation files $finder = new Finder(); $files = $finder->files()->name('*.' . $input->getArgument('locale') . '.php')->in($bundleTransPath); foreach ($files as $file) { $output->writeln(sprintf(' > parsing translation <comment>%s</comment>', $file->getPathname())); $domain = substr($file->getFileName(), 0, strrpos($file->getFileName(), $input->getArgument('locale') . '.php') - 1); $loader = new \Symfony\Component\Translation\Loader\PhpFileLoader(); $this->messages->addCatalogue($loader->load($file->getPathname(), $input->getArgument('locale'), $domain)); } // load any existing pot translation files $finder = new Finder(); $files = $finder->files()->name('*.' . $input->getArgument('locale') . '.pot')->in($bundleTransPath); foreach ($files as $file) { $output->writeln(sprintf(' > parsing translation <comment>%s</comment>', $file->getPathname())); $domain = substr($file->getFileName(), 0, strrpos($file->getFileName(), $input->getArgument('locale') . '.pot') - 1); $loader = new \BCC\ExtraToolsBundle\Translation\Loader\PotFileLoader(); $this->messages->addCatalogue($loader->load($file->getPathname(), $input->getArgument('locale'), $domain)); } // show compiled list of messages if($input->getOption('dump-messages') === true){ foreach ($this->messages->getDomains() as $domain) { $output->writeln(sprintf("\nDisplaying messages for domain <info>%s</info>:\n", $domain)); $output->writeln(\Symfony\Component\Yaml\Yaml::dump($this->messages->all($domain),10)); } } // save the files if($input->getOption('force') === true) { $output->writeln("\nWriting files.\n"); $path = $foundBundle->getPath() . '/Resources/translations/'; if ($input->getOption('output-format') == 'yml') { $formatter = new \BCC\ExtraToolsBundle\Translation\Formatter\YmlFormatter(); } elseif ($input->getOption('output-format') == 'php') { $formatter = new \BCC\ExtraToolsBundle\Translation\Formatter\PhpFormatter(); } elseif ($input->getOption('output-format') == 'pot') { $formatter = new \BCC\ExtraToolsBundle\Translation\Formatter\PotFormatter(); } else { $formatter = new \BCC\ExtraToolsBundle\Translation\Formatter\XliffFormatter($input->getOption('source-lang')); } foreach ($this->messages->getDomains() as $domain) { $file = $domain . '.' . $input->getArgument('locale') . '.' . $input->getOption('output-format'); if (file_exists($path . $file)) { copy($path . $file, $path . '~' . $file . '.bak'); } $output->writeln(sprintf(' > generating <comment>%s</comment>', $path . $file)); file_put_contents($path . $file, $formatter->format($this->messages->all($domain))); } } } }
protected function compareDbWithFiles(MessageCatalogue $globalCatalogue) { $domains = $globalCatalogue->getDomains(); if (!count($domains)) { return []; } $dbData = $this->getEntityManager()->getRepository('OctavaMuiBundle:Translation')->findAll(); $filesData = $globalCatalogue->all(); $result = []; foreach ($dbData as $dbItem) { if (!isset($filesData[$dbItem->getDomain()][$dbItem->getSource()])) { $result[$dbItem->getDomain()][] = $dbItem->getSource(); } } return $result; }
/** * Сохраняет переводы в БД * @param MessageCatalogue $messages * @param bool $overwriteExisting - перезаписывать существующие переводы * @param bool $addNew - добавлять новые метки если они найдены в каталоге */ public function saveTranslations(MessageCatalogue $messages, $overwriteExisting = false, $addNew = false) { $locale = $messages->getLocale(); $domains = $messages->getDomains(); if (!count($domains)) { return; } $logger = $this->getLogger(); $logger->info("Start import"); $entities = $this->getEntityManager()->getRepository('OctavaMuiBundle:Translation')->getTranslationsByDomains($domains); $currentData = []; foreach ($entities as $item) { $currentData[$item->getDomain()][$item->getSource()] = $item; } foreach ($domains as $domain) { foreach ($messages->all($domain) as $source => $target) { $entity = null; if (isset($currentData[$domain]) && isset($currentData[$domain][$source])) { $entity = $currentData[$domain][$source]; } $needToPersist = false; if ($entity instanceof Translation) { $translation = $entity->getTranslations(); if (!isset($translation[$locale]) || $translation[$locale] == '' && $target != '' || $overwriteExisting && $translation[$locale] != $target) { $oldValue = isset($translation[$locale]) ? $translation[$locale] : null; $translation[$locale] = $target; ksort($translation); $entity->setTranslations($translation); $needToPersist = true; $this->importLog[] = ['action' => 'update', 'locale' => $locale, 'domain' => $domain, 'source' => $source, 'old_value' => $oldValue, 'target' => $target]; } } else { if ($addNew) { $entity = new Translation(); $entity->setDomain($domain)->setSource($source)->setTranslations([$locale => $target]); $needToPersist = true; $this->importLog[] = ['action' => 'add', 'locale' => $locale, 'domain' => $domain, 'source' => $source, 'old_value' => '', 'target' => $target]; } } if ($needToPersist) { $this->getEntityManager()->persist($entity); } } } foreach ($this->importLog as $message) { $logger->info(json_encode($message)); } $logger->info("Finish import"); $this->getEntityManager()->flush(); $this->clearCache(); }