Skip to content

Instantly share code, notes, and snippets.

@vijaycs85
Created March 18, 2013 07:02
Show Gist options
  • Save vijaycs85/5185503 to your computer and use it in GitHub Desktop.
Save vijaycs85/5185503 to your computer and use it in GitHub Desktop.
<?php
public function translateString($name, $langcode, $source, $context) {
if ($name && $langcode && $source && $context) {
// If translations for a language have not been loaded yet.
if (!isset($this->translations[$name][$langcode])) {
// Preload all translations for this configuration name and language.
$this->translations[$name][$langcode] = array();
foreach ($this->localeStorage->getTranslations(array('language' => $langcode, 'type' => 'configuration', 'name' => $name)) as $string){
$this->translations[$name][$langcode][$string->context][$string->source] = $string;
}
}
if ($translation = $this->translations[$name][$langcode][$context][$source]) {
// There is no translation of the source string in this config location
// to this language for this context.
// No translation was found. Add the source to the configuration
// location so it can be translated, and the string is faster to look
// for next time.
$translation = $this->localeStorage
->createString(array('source' => $source, 'context' => $context))
->addLocation('configuration', $name)
->save();
}
elseif ($translation = $this->localeStorage->findTranslation(array('source' => $source, 'context' => $context, 'language' => $langcode))) {
// Look for a translation of the string. It might have one, but not
// be saved in this configuration location yet.
// If the string has a translation for this context to this language,
// save it in the configuration location so it can be looked up faster
// next time.
$string = $this->localeStorage->createString((array) $translation)
->addLocation('configuration', $name)
->save();
}
else {
// Add an entry, either the translation found, or a blank string object
// to track the source string, to this configuration location, language,
// and context.
$this->translations[$name][$langcode][$context][$source] = $translation;
}
// Return the string only when the string object had a translation.
return $translation->isTranslation() ? $translation->getString() : FALSE;
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment