本文整理汇总了PHP中Gettext\Translations::fromPoFile方法的典型用法代码示例。如果您正苦于以下问题:PHP Translations::fromPoFile方法的具体用法?PHP Translations::fromPoFile怎么用?PHP Translations::fromPoFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Gettext\Translations
的用法示例。
在下文中一共展示了Translations::fromPoFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->writeSection($output, 'Po to Csv converter');
$this->cwd = getcwd() . DIRECTORY_SEPARATOR;
$output->writeln('<info>Using CWD</info> ' . $this->cwd);
$poFiles = $this->getInputPoFiles($input, $output);
$outputFolder = $this->getOutputFolder($input, $output);
$useDefaults = $input->getOption('use-defaults');
if ($useDefaults) {
$output->writeln('<info>Po files</info>:');
$this->writeList($output, $poFiles);
$output->writeln(['', '<info>Output folder</info>: ' . $outputFolder]);
}
$poHandles = [];
foreach ($poFiles as $poFile) {
$key = basename($poFile, '.po');
$output->writeln('<info>loading ' . $key . '</info>...');
$poHandles[$key] = Translations::fromPoFile($poFile);
}
$output->writeln('<info>merging po files</info>...');
$csvArray = [];
foreach ($poHandles as $language => $poHandle) {
foreach ($poHandle as $translation) {
$original = trim($translation->original);
$translation = trim($translation->translation);
if (!isset($csvArray[$original])) {
$csvArray[$original] = [$language => $translation];
} elseif (!isset($csvArray[$original][$language])) {
$csvArray[$original][$language] = $translation;
} elseif ($csvArray[$original][$language] != $translation) {
$csvArray[$original][$language] = $this->handleConflict($input, $output, $original, $csvArray[$original][$language], $translation);
}
}
}
$output->writeln('<info>writing csv</info>...');
$writer = Writer::createFromFileObject(new SplTempFileObject());
$writer->setDelimiter(';');
$header = ['original'];
$header = array_merge($header, array_keys($poHandles));
$writer->insertOne($header);
foreach ($csvArray as $original => $item) {
$row = [];
foreach ($header as $column) {
if ($column === 'original') {
$row[] = $original;
} else {
$row[] = isset($item[$column]) ? $item[$column] : null;
}
}
$writer->insertOne($row);
}
$outputFile = $outputFolder . DIRECTORY_SEPARATOR . 'translations.csv';
file_put_contents($outputFile, $writer->__toString());
$output->writeln('<info>done. output file is</info> ' . $outputFile);
}
示例2: register
public function register(Fol $app)
{
$app['middleware'] = function ($app) {
$middleware = [];
if ($app->has('users')) {
$middleware[] = new Middlewares\DigestAuthentication($app['users']);
}
$middleware[] = new Middlewares\Expires();
$middleware[] = (new Middlewares\ErrorHandler())->catchExceptions()->statusCode(function ($code) {
return $code > 400 && $code < 600;
})->arguments($app);
$middleware[] = new Middlewares\BasePath($app->getUrlPath());
$middleware[] = new Middlewares\TrailingSlash();
$middleware[] = new Middlewares\ContentType();
$middleware[] = new Middlewares\ContentLanguage(['en', 'gl', 'es']);
$middleware[] = function ($request, $next) use($app) {
$language = $request->getHeaderLine('Accept-Language');
$translator = new Translator();
$translator->loadTranslations(Translations::fromPoFile(dirname(dirname(__DIR__)) . '/locales/' . $language . '.po'));
$prev = $translator->register();
$app['templates']->addData(['language' => $language]);
$response = $next($request);
if ($prev) {
$prev->register();
}
return $response;
};
$middleware[] = (new Middlewares\MethodOverride())->parsedBodyParameter('method-override');
$middleware[] = (new Middlewares\Reader(dirname(dirname(__DIR__)) . '/assets'))->continueOnError();
$middleware[] = (new Middlewares\AuraRouter($app['router']))->arguments($app);
return new Dispatcher($middleware);
};
}
示例3: main
/**
* main
*
*/
public function main()
{
$default = APP . 'Locale' . DS . 'default.pot';
$response = $this->in("What is the full path you would like to merge file (created pot file)?\nExample:" . $default . "\n[Q]uit", null, $default);
if (strtoupper($response) === 'Q') {
$this->out('Merge Aborted');
$this->_stop();
}
$created = new File($response, false, 0755);
if (!$created->exists()) {
$this->err('The file path you supplied was not found. Please try again.');
$this->_stop();
}
$default = APP . 'Locale' . DS . 'ja' . DS . 'default.po';
$response = $this->in("What is the full path you would like to merge file (current po file)?\nExample: " . $default . "\n[Q]uit", null, $default);
if (strtoupper($response) === 'Q') {
$this->out('Merge Aborted');
$this->_stop();
}
$current = new File($response, false, 0755);
if (!$current->exists()) {
$this->err('The file path you supplied was not found. Please try again.');
$this->_stop();
}
$createdTranslations = Translations::fromPoFile($created->path);
$createdTranslations->addFromPoFile($current->path);
$merged = $createdTranslations->toPoString();
$this->createFile($current->path, $merged);
}
示例4: load_translation
/**
* Load the i12n translation file.
*/
public function load_translation()
{
$translator = new \Gettext\Translator();
$i18n_path = realpath(__DIR__ . '/../../i18n/' . Config::$locale . '.po');
if (file_exists($i18n_path)) {
$translations = \Gettext\Translations::fromPoFile($i18n_path);
$translator->loadTranslations($translations);
}
Translator::initGettextFunctions($translator);
}
示例5: loadTranslations
protected function loadTranslations()
{
if (!file_exists($this->arguments['src-po'])) {
$this->error('src-po file not found');
exit;
}
$this->translations = Translations::fromPoFile($this->arguments['src-po']);
list($code) = explode('_', $this->translations->getLanguage());
$this->translateDirection = ($this->arguments['src-lang'] ?: 'en') . '-' . $code;
}
示例6: updateFromCatalog
/**
* Updates the catalog file from the given po file
*
* @return void
*/
public function updateFromCatalog()
{
$domain = $this->params['domain'];
#$localePaths = App::path('Locale');
$localePath = ROOT . '/src/Locale/';
$catalogFile = $localePath . $domain . '.pot';
if (!file_exists($catalogFile)) {
return $this->abort(sprintf('Catalog File %s not found.', $catalogFile));
}
$poFiles = [];
$folder = new Folder($localePath);
$tree = $folder->tree();
foreach ($tree[1] as $file) {
$basename = basename($file);
if ($domain . '.po' === $basename) {
$poFiles[] = $file;
}
}
if (empty($poFiles)) {
return $this->abort('I could not find any matching po files in the given locale path (%s) for the domain (%s)', $localePath, $domain);
}
if (!$this->params['overwrite']) {
$this->out('I will update the following .po files and their corresponding .mo file with the keys from catalog: ' . $catalogFile);
foreach ($poFiles as $poFile) {
$this->out(' - ' . $poFile);
}
$response = $this->in('Would you like to continue?', ['y', 'n'], 'n');
if ($response !== 'y') {
return $this->abort('Aborted');
}
}
foreach ($poFiles as $poFile) {
$catalogEntries = Translations::fromPoFile($catalogFile);
$moFile = str_replace('.po', '.mo', $poFile);
$translationEntries = Translations::fromPoFile($poFile);
$newTranslationEntries = $catalogEntries->mergeWith($translationEntries, Merge::REFERENCES_THEIRS);
$newTranslationEntries->deleteHeaders();
foreach ($translationEntries->getHeaders() as $key => $value) {
$newTranslationEntries->setHeader($key, $value);
}
if ($this->params['strip-references']) {
foreach ($newTranslationEntries as $translation) {
$translation->deleteReferences();
}
}
$newTranslationEntries->toPoFile($poFile);
$newTranslationEntries->toMoFile($moFile);
$this->out('Updated ' . $poFile);
$this->out('Updated ' . $moFile);
}
}
示例7: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$filesystem = new Filesystem();
$locator = $container->get("agit.common.filecollector");
$bundles = $container->getParameter("kernel.bundles");
$catalogPath = $container->getParameter("kernel.root_dir") . "/{$this->catalogSubdir}";
$this->getContainer()->get("event_dispatcher")->dispatch("agit.intl.global.translations", new TranslationsEvent($this));
foreach ($container->getParameter("agit.intl.locales") as $locale) {
$catalog = new Translations();
$messagesPath = "{$catalogPath}/{$locale}/LC_MESSAGES";
$catalogFile = "{$messagesPath}/agit.po";
$oldCatalog = $filesystem->exists($catalogFile) ? Translations::fromPoFile($catalogFile) : new Translations();
foreach ($oldCatalog as $translation) {
$translation->deleteReferences();
}
$catalog->mergeWith($oldCatalog, 0);
foreach ($bundles as $alias => $namespace) {
$bundlePath = $locator->resolve($alias);
$bundleCatalogFile = "{$bundlePath}/{$this->catalogSubdir}/bundle.{$locale}.po";
$bundleCatalog = $filesystem->exists($bundleCatalogFile) ? Translations::fromPoFile($bundleCatalogFile) : new Translations();
$catalog->mergeWith($bundleCatalog, Merge::ADD);
}
if (isset($this->extraTranslations[$locale])) {
foreach ($this->extraTranslations[$locale] as $translation) {
$catalog[] = $translation;
}
}
// NOTE: we delete all headers and only set language in order to avoid garbage commits
$catalog->deleteHeaders();
$catalog->setLanguage($locale);
$catalog->setHeader("Content-Type", "text/plain; charset=UTF-8");
$filesystem->dumpFile($catalogFile, $catalog->toPoString());
$filesystem->dumpFile("{$messagesPath}/agit.mo", $catalog->toMoString());
}
}
示例8: generateTranslationFiles
public function generateTranslationFiles(Locale $locale, $activeTranslations = null)
{
$envPoFile = $locale->getPoFilePath(WP_ENV);
$poFile = $locale->getPoFilePath();
$moFile = $locale->getMoFilePath();
if (is_null($activeTranslations)) {
$activeTranslations = $locale->hasPoFile() ? Translations::fromPoFile($locale->getPoFilePath()) : new Translations();
}
// Add local modifications to the default set should there
// be any.
if ($locale->hasPoFile(WP_ENV)) {
$this->hardTranslationSetMerge($locale, Translations::fromPoFile($envPoFile), $activeTranslations);
}
$textDomain = Strata::i18n()->getTextdomain();
$activeTranslations->setDomain($textDomain);
$activeTranslations->setHeader('Language', $locale->getCode());
$activeTranslations->setHeader('Text Domain', $textDomain);
$activeTranslations->setHeader('X-Domain', $textDomain);
@unlink($poFile);
@unlink($moFile);
$activeTranslations->toPoFile($poFile);
$activeTranslations->toMoFile($moFile);
}
示例9: addTranslation
/**
* @param string $path
*/
public static function addTranslation($path)
{
$file = new File($path);
if ($file->exists()) {
$parts = explode('.', $path);
$extension = $parts[count($parts) - 1];
switch ($extension) {
case 'po':
$translations = Translations::fromPoFile($path);
break;
case 'mo':
$translations = Translations::fromMoFile($path);
break;
case 'php':
$translations = Translations::fromPhpArrayFile($path);
break;
}
self::$activeTranslation->mergeWith($translations);
self::$t->loadTranslations(self::$activeTranslation);
}
}
示例10: updateMO
public static function updateMO()
{
$path = base_path() . "/" . dirname(self::getFile(self::$locale));
$file = $path . '/' . self::$config['domain'];
$translations = Translations::fromPoFile($file . '.po');
$translations->toMoFile($file . '.mo');
}
示例11: loadGettextGettextFromPO
/**
* Load translation domain from Gettext/Gettext using .po
*
* Note: Since Twig I18N does not support domains, all loaded files are
* merged. Use contexts if identical strings need to be disambiguated.
*
* @param string $domain Name of domain
* @param boolean $catchException Whether to catch an exception on error or return early
*
* @throws \Exception If something is wrong with the locale file for the domain and activated language
*/
private function loadGettextGettextFromPO($domain = self::DEFAULT_DOMAIN, $catchException = true)
{
try {
$langPath = $this->getLangPath($domain);
} catch (\Exception $e) {
$error = "Something went wrong when trying to get path to language file, cannot load domain '{$domain}'.";
\SimpleSAML\Logger::error($_SERVER['PHP_SELF'] . ' - ' . $error);
if ($catchException) {
// bail out!
return;
} else {
throw $e;
}
}
$poFile = $domain . '.po';
$poPath = $langPath . $poFile;
if (file_exists($poPath) && is_readable($poPath)) {
$translations = Translations::fromPoFile($poPath);
$this->translator->loadTranslations($translations);
} else {
$error = "Localization file '{$poFile}' not found in '{$langPath}', falling back to default";
\SimpleSAML\Logger::error($_SERVER['PHP_SELF'] . ' - ' . $error);
}
}
示例12: load
public static function load()
{
$locale = self::$locale . '.UTF-8';
# IMPORTANT: locale must be installed in server!
# sudo locale-gen es_ES.UTF-8
# sudo update-locale
putenv('LANG=' . $locale);
putenv('LANGUAGE=' . $locale);
putenv('LC_MESSAGES=' . $locale);
putenv('LC_PAPER=' . $locale);
putenv('LC_TIME=' . $locale);
putenv('LC_MONETARY=' . $locale);
setlocale(LC_MESSAGES, $locale);
setlocale(LC_COLLATE, $locale);
setlocale(LC_TIME, $locale);
setlocale(LC_MONETARY, $locale);
bindtextdomain(self::$config['domain'], self::$config['storage']);
bind_textdomain_codeset(self::$config['domain'], 'UTF-8');
textdomain(self::$config['domain']);
# Also, we will work with gettext/gettext library
# because PHP gones crazy when mo files are updated
$path = dirname(self::getFile(self::$locale));
$file = $path . '/' . self::$config['domain'];
if (is_file($file . '.php')) {
$translations = $file . '.php';
} elseif (is_file($file . '.mo')) {
$translations = Translations::fromMoFile($file . '.mo');
} elseif (is_file($file . '.po')) {
$translations = Translations::fromPoFile($file . '.po');
} else {
$translations = new Translations();
}
Translator::initGettextFunctions((new Translator())->loadTranslations($translations));
}
示例13: array
<?php
require '../vendor/autoload.php';
use Gettext\Translations;
use Gettext\Translator;
$locales = array('en', 'es', 'nb');
$text = "Hello, untranslated world!";
echo "<p>Original string: {$text}</p>";
foreach ($locales as $locale) {
// START setup
echo '<p>';
echo "Trying to set locale: {$locale}";
echo '<br>';
$translations = Translations::fromPoFile("../locale/{$locale}/LC_MESSAGES/test1.po");
echo '<br>';
$t = new Translator();
$t->loadTranslations($translations);
Translator::initGettextFunctions($t);
// END setup
echo __($text);
echo '<br>';
echo '</p>';
}
示例14: loadFormatPo
private static function loadFormatPo($file)
{
return is_file($file . '.po') ? Translations::fromPoFile($file . '.po') : null;
}
示例15: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$filesystem = new Filesystem();
$bundleAlias = $input->getArgument("bundle");
$bundlePath = $container->get("agit.common.filecollector")->resolve($bundleAlias);
$defaultLocale = $container->get("agit.intl.locale")->getDefaultLocale();
$locales = $input->getArgument("locales") ? array_map("trim", explode(",", $input->getArgument("locales"))) : $container->getParameter("agit.intl.locales");
$globalCatalogPath = $container->getParameter("kernel.root_dir") . "/{$this->catalogSubdir}";
$this->cacheBasePath = sprintf("%s/agit.intl.temp/%s", sys_get_temp_dir(), $bundleAlias);
$filesystem->mkdir($this->cacheBasePath);
$finder = (new Finder())->in("{$bundlePath}")->name("*\\.php")->name("*\\.js")->notPath("/test.*/i")->notPath("public/js/ext");
$files = [];
foreach ($finder as $file) {
$filePath = $file->getRealpath();
$alias = str_replace($bundlePath, "@{$bundleAlias}/", $filePath);
$files[$filePath] = $alias;
}
$this->getContainer()->get("event_dispatcher")->dispatch("agit.intl.bundle.files", new BundleTranslationFilesEvent($this, $bundleAlias, $this->cacheBasePath));
$this->extraTranslations = new Translations();
$this->getContainer()->get("event_dispatcher")->dispatch("agit.intl.bundle.translations", new BundleTranslationsEvent($this, $bundleAlias));
$files += $this->extraSourceFiles;
$frontendFiles = array_filter(array_keys($files), function ($file) {
return preg_match("|\\.js\$|", $file);
});
$backendFiles = array_filter(array_keys($files), function ($file) {
return !preg_match("|\\.js\$|", $file);
});
$frontendCatalogs = "";
foreach ($locales as $locale) {
if (!preg_match("|^[a-z]{2}_[A-Z]{2}|", $locale)) {
throw new Exception("Invalid locale: {$locale}");
}
// we use the global catalog as source for already translated strings
$globalCatalogFile = "{$globalCatalogPath}/{$locale}/LC_MESSAGES/agit.po";
$globalCatalog = $filesystem->exists($globalCatalogFile) ? $this->deleteReferences(Translations::fromPoFile($globalCatalogFile)) : new Translations();
$bundleCatalogFile = "{$bundlePath}/{$this->catalogSubdir}/bundle.{$locale}.po";
$oldBundleCatalog = $filesystem->exists($bundleCatalogFile) ? $this->deleteReferences(Translations::fromPoFile($bundleCatalogFile)) : new Translations();
// NOTE: we delete all headers and only set language, in order to avoid garbage commits
$bundleCatalog = new Translations();
$bundleCatalog->deleteHeaders();
$bundleCatalog->setLanguage($locale);
// first: only JS messages
foreach ($frontendFiles as $file) {
$bundleCatalog->addFromJsCodeFile($file, $this->extractorOptions);
}
$bundleCatalog->mergeWith($oldBundleCatalog, 0);
$bundleCatalog->mergeWith($globalCatalog, 0);
if ($bundleCatalog->count() && $locale !== $defaultLocale) {
$transMap = [];
foreach ($bundleCatalog as $entry) {
$msgid = ltrim($entry->getId(), "");
$msgstr = $entry->getTranslation();
$transMap[$msgid] = $entry->hasPlural() ? array_merge([$msgstr], $entry->getPluralTranslations()) : $msgstr;
}
$frontendCatalogs .= sprintf("ag.intl.register(\"%s\", %s);\n\n", $locale, json_encode($transMap, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
}
// now the same with all messages
foreach ($backendFiles as $file) {
$bundleCatalog->addFromPhpCodeFile($file, $this->extractorOptions);
}
$bundleCatalog->mergeWith($this->extraTranslations, Merge::ADD);
$bundleCatalog->mergeWith($oldBundleCatalog, 0);
$bundleCatalog->mergeWith($globalCatalog, 0);
$catalog = $bundleCatalog->toPoString();
$catalog = str_replace(array_keys($files), array_values($files), $catalog);
if ($bundleCatalog->count()) {
$filesystem->dumpFile("{$bundlePath}/{$this->catalogSubdir}/bundle.{$locale}.po", $catalog);
}
}
if ($frontendCatalogs) {
$filesystem->dumpFile("{$bundlePath}/{$this->frontendSubdir}/translations.js", $frontendCatalogs);
}
$filesystem->remove($this->cacheBasePath);
}