Example #1
0
 /**	@brief Changement de langue.
  * 
  * Exploitation du cache de l'application pour stocker l'instance de Zend_Translate correspondant.
  * Si le cache n'est pas présent, une nouvelle instance est créée, puis stockée dans le cache de Zend_Translate.
  * 
  * @see		Controller/Plugin/Zend_Controller_Plugin_Abstract::routeShutdown()
  * @throws	exception Projet_Exception en cas d'erreur au cours de la requête.
  * @return	void.
  */
 public function routeShutdown(Zend_Controller_Request_Abstract $request)
 {
     parent::routeShutdown($request);
     // Récupération du paramètre de langue passée dans l'URL
     $sLocal = $this->getRequest()->getParam('language') ? $this->getRequest()->getParam('language') : self::DEFAULT_LANGUAGE;
     // Récupération du local dans une combinaison du type "fr_FR"
     $aLanguage = explode("_", $sLocal);
     $sLanguage = isset($aLanguage[0]) ? $aLanguage[0] : self::DEFAULT_LANGUAGE;
     # Récupération de "fr"
     $sCountry = isset($aLanguage[1]) ? $aLanguage[1] : self::DEFAULT_COUNTRY;
     # Récupération de "FR"
     // Fonctionnalité réalisée si le fichier de langue n'existe pas
     if (!file_exists(LANGUAGE_PATH . $sLanguage . '.ini')) {
         $sLanguage = self::DEFAULT_LANGUAGE;
     }
     // Récupération du cache de la langue en cours dans le cache de Zend_Translate
     if ((bool) APP_CACHE) {
         $oCacheTranslate = Zend_Translate::getCache();
         $oTranslate = $oCacheTranslate->load($sLanguage);
     } else {
         $oTranslate = null;
     }
     // Fonctionnalité réalisé si
     if (empty($oTranslate)) {
         // Initialisation de la langue
         try {
             // Chargement du Zend_Translate
             $oTranslate = new Zend_Translate(array('adapter' => 'ini', 'content' => LANGUAGE_PATH . $sLanguage . '.ini', 'locale' => $sLocal));
             $sFichier = LANGUAGE_PATH . $sLanguage . '.php';
             if (file_exists($sFichier)) {
                 //traduction des erreurs de formulaires
                 $oTranslate->addTranslation(array('content' => new Zend_Translate('array', $sFichier, $sLanguage)));
             }
             if ((bool) APP_CACHE) {
                 // Enregistrement de la langue dans le cache
                 $oCacheTranslate = Zend_Translate::getCache();
                 $oCacheTranslate->save($oTranslate, $sLanguage);
             }
         } catch (Exception $e) {
             if ((bool) APP_CACHE) {
                 // Suppression du cache
                 $oCacheTranslate->remove($sLanguage);
             }
             // Création d'une exception au niveau du projet
             die($e->getMessage());
             throw new Projet_Exception($e->getMessage(), __METHOD__, $e);
         }
     }
     // Enregistrement du Zend_Translate dans les fonctionnalités de l'application
     Zend_Registry::set("Zend_Locale", $sLocal);
     Zend_Registry::set("Zend_Translate", $oTranslate);
     // Potentiellement inutile vu la ligne précédente...
     Zend_Form::setDefaultTranslator($oTranslate);
     Zend_Validate_Abstract::setDefaultTranslator($oTranslate);
     // Language par défaut pour toutes les routes
     Zend_Controller_Front::getInstance()->getRouter()->setGlobalParam('language', $sLocal);
 }
 /**
  * @return array Array of priority keys to instances of Zend_Translate, mapped by name.
  */
 public static function get_translators()
 {
     if (!Zend_Translate::getCache()) {
         Zend_Translate::setCache(self::get_cache());
     }
     if (!self::$translators) {
         $defaultPriority = 10;
         self::$translators[$defaultPriority] = array('core' => new Zend_Translate(array('adapter' => 'i18nRailsYamlAdapter', 'locale' => self::$default_locale, 'disableNotices' => true)));
         i18n::include_by_locale('en');
         i18n::include_by_locale('en_US');
     }
     return self::$translators;
 }
 /**
  * ZF-9877
  */
 public function testSetCacheThroughOptions()
 {
     require_once 'Zend/Cache.php';
     $cache = Zend_Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => dirname(__FILE__) . '/_files/'));
     $translate = new Zend_Translate(array('adapter' => Zend_Translate::AN_ARRAY, 'content' => array('msg1' => 'Message 1 (en)'), 'locale' => 'en', 'cache' => $cache));
     $return = Zend_Translate::getCache();
     $this->assertTrue($return instanceof Zend_Cache_Core);
     $this->assertTrue(Zend_Translate::hasCache());
 }
Example #4
0
 /**
  * Includes all available language files for a certain defined locale.
  *
  * @param string $locale All resources from any module in locale $locale will be loaded
  * @param Boolean $clean Clean old caches?
  */
 public static function include_by_locale($locale, $clean = false)
 {
     if ($clean) {
         $cache = Zend_Translate::getCache();
         if ($cache) {
             $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
         }
     }
     // Sort modules by inclusion priority, then alphabetically
     // TODO Should be handled by priority flags within modules
     $prios = array('sapphire' => 10, 'framework' => 10, 'admin' => 11, 'cms' => 12, 'mysite' => 90);
     $modules = SS_ClassLoader::instance()->getManifest()->getModules();
     ksort($modules);
     uksort($modules, function ($a, $b) use(&$prios) {
         $prioA = isset($prios[$a]) ? $prios[$a] : 50;
         $prioB = isset($prios[$b]) ? $prios[$b] : 50;
         return $prioA > $prioB;
     });
     // Loop in reverse order, meaning the translator with the highest priority goes first
     $translators = array_reverse(self::get_translators(), true);
     foreach ($translators as $priority => $translators) {
         foreach ($translators as $name => $translator) {
             $adapter = $translator->getAdapter();
             // Load translations from modules
             foreach ($modules as $module) {
                 $filename = $adapter->getFilenameForLocale($locale);
                 $filepath = "{$module}/lang/" . $filename;
                 if ($filename && !file_exists($filepath)) {
                     continue;
                 }
                 $adapter->addTranslation(array('content' => $filepath, 'locale' => $locale));
             }
             // Load translations from themes
             // TODO Replace with theme listing once implemented in TemplateManifest
             $themesBase = Director::baseFolder() . '/themes';
             if (is_dir($themesBase)) {
                 foreach (scandir($themesBase) as $theme) {
                     if (strpos($theme, SSViewer::current_theme()) === 0 && file_exists("{$themesBase}/{$theme}/lang/")) {
                         $filename = $adapter->getFilenameForLocale($locale);
                         $filepath = "{$themesBase}/{$theme}/lang/" . $filename;
                         if ($filename && !file_exists($filepath)) {
                             continue;
                         }
                         $adapter->addTranslation(array('content' => $filepath, 'locale' => $locale));
                     }
                 }
             }
             // Add empty translations to ensure the locales are "registered" with isAvailable(),
             // and the next invocation of include_by_locale() doesn't cause a new reparse.
             $adapter->addTranslation(array('content' => array($locale => $locale), 'locale' => $locale, 'usetranslateadapter' => true));
         }
     }
 }
Example #5
0
 /**
  * @group ZF-10034
  */
 public function testSetCacheFromCacheManager()
 {
     $configCache = array('translate' => array('frontend' => array('name' => 'Core', 'options' => array('lifetime' => 120, 'automatic_serialization' => true)), 'backend' => array('name' => 'Black Hole')));
     $this->bootstrap->registerPluginResource('cachemanager', $configCache);
     $options = $this->_translationOptions;
     $options['cache'] = 'translate';
     $resource = new Zend_Application_Resource_Translate($options);
     $resource->setBootstrap($this->bootstrap);
     $resource->init();
     $this->assertTrue(Zend_Translate::getCache() instanceof Zend_Cache_Core);
     Zend_Translate::removeCache();
 }
 /**
  * test cache object settings
  */
 public function testCache()
 {
     $cache = Zend_Registry::get('cache');
     $this->assertEquals('Zend_Cache_Core', get_class($cache));
     $this->assertEquals($cache, Zend_Locale::getCache());
     $this->assertEquals($cache, Zend_Translate::getCache());
     $this->assertEquals('Zend_Cache_Backend_File', get_class($cache->getBackend()));
 }
Example #7
0
 public function testTestingCacheHandling()
 {
     require_once 'Zend/Cache.php';
     $cache = Zend_Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => dirname(__FILE__) . '/_files/'));
     Zend_Translate::setCache($cache);
     $cache = Zend_Translate::getCache();
     $this->assertTrue($cache instanceof Zend_Cache_Core);
     $this->assertTrue(Zend_Translate::hasCache());
     $lang = new Zend_Translate(Zend_Translate::AN_ARRAY, array('msg1' => 'Message 1 (en)'), 'en');
     $adapter = $lang->getAdapter();
     $this->assertTrue($adapter instanceof Zend_Translate_Adapter_Array);
     $adaptercache = $adapter->getCache();
     $this->assertTrue($adaptercache instanceof Zend_Cache_Core);
     Zend_Translate::clearCache();
     $this->assertTrue(Zend_Translate::hasCache());
     Zend_Translate::removeCache();
     $this->assertFalse(Zend_Translate::hasCache());
 }
Example #8
0
 public function testShareCacheToZendObjects()
 {
     $resource = new Zend_Application_Resource_Cache(array('frontend' => array('class' => 'core'), 'backend' => array('class' => 'file'), 'sharetozendobjects' => null));
     $cache = $resource->init();
     $this->assertEquals($cache, Zend_Translate::getCache());
     /**
      * @todo Zend_Paginator::getCache() missing
      * $this->assertEquals($cache, Zend_Paginator::getCache());
      */
     $this->assertEquals($cache, Zend_Locale::getCache());
     $this->assertEquals($cache, Zend_Db_Table::getDefaultMetadataCache());
     $this->assertEquals($cache, Zend_Locale_Data::getCache());
 }
 /**
  * @return array Array of priority keys to instances of Zend_Translate, mapped by name.
  */
 public static function get_translators()
 {
     if (!Zend_Translate::getCache()) {
         Zend_Translate::setCache(SS_Cache::factory('i18n', 'Output', array('lifetime' => null, 'automatic_serialization' => true)));
     }
     if (!self::$translators) {
         $defaultPriority = 10;
         self::$translators[$defaultPriority] = array('core' => new Zend_Translate(array('adapter' => 'i18nRailsYamlAdapter', 'locale' => self::$default_locale, 'disableNotices' => true)));
         i18n::include_by_locale('en', isset($_GET['flush']));
         i18n::include_by_locale('en_US', isset($_GET['flush']));
     }
     return self::$translators;
 }
Example #10
0
 /**
  * Includes all available language files for a certain defined locale.
  *
  * @param string $locale All resources from any module in locale $locale will be loaded
  * @param Boolean $clean Clean old caches?
  */
 public static function include_by_locale($locale, $clean = false)
 {
     if ($clean) {
         $cache = Zend_Translate::getCache();
         if ($cache) {
             $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
         }
     }
     // Get list of module => path pairs, and then just the names
     $modules = SS_ClassLoader::instance()->getManifest()->getModules();
     $moduleNames = array_keys($modules);
     // Remove the "project" module from the list - we'll add it back specially later if needed
     global $project;
     if (($idx = array_search($project, $moduleNames)) !== false) {
         array_splice($moduleNames, $idx, 1);
     }
     // Get the order from the config syste,
     $order = Config::inst()->get('i18n', 'module_priority');
     // Find all modules that don't have their order specified by the config system
     $unspecified = array_diff($moduleNames, $order);
     // If the placeholder "other_modules" exists in the order array, replace it by the unspecified modules
     if (($idx = array_search('other_modules', $order)) !== false) {
         array_splice($order, $idx, 1, $unspecified);
     } else {
         array_splice($order, 0, 0, $unspecified);
     }
     // Put the project module back in at the begining if it wasn't specified by the config system
     if (!in_array($project, $order)) {
         array_unshift($order, $project);
     }
     $sortedModules = array();
     foreach ($order as $module) {
         if (isset($modules[$module])) {
             $sortedModules[$module] = $modules[$module];
         }
     }
     $sortedModules = array_reverse($sortedModules, true);
     // Loop in reverse order, meaning the translator with the highest priority goes first
     $translators = array_reverse(self::get_translators(), true);
     foreach ($translators as $priority => $translators) {
         foreach ($translators as $name => $translator) {
             $adapter = $translator->getAdapter();
             // Load translations from modules
             foreach ($sortedModules as $module) {
                 $filename = $adapter->getFilenameForLocale($locale);
                 $filepath = "{$module}/lang/" . $filename;
                 if ($filename && !file_exists($filepath)) {
                     continue;
                 }
                 $adapter->addTranslation(array('content' => $filepath, 'locale' => $locale));
             }
             // Load translations from themes
             // TODO Replace with theme listing once implemented in TemplateManifest
             $themesBase = Director::baseFolder() . '/themes';
             if (is_dir($themesBase)) {
                 foreach (scandir($themesBase) as $theme) {
                     if (strpos($theme, Config::inst()->get('SSViewer', 'theme')) === 0 && file_exists("{$themesBase}/{$theme}/lang/")) {
                         $filename = $adapter->getFilenameForLocale($locale);
                         $filepath = "{$themesBase}/{$theme}/lang/" . $filename;
                         if ($filename && !file_exists($filepath)) {
                             continue;
                         }
                         $adapter->addTranslation(array('content' => $filepath, 'locale' => $locale));
                     }
                 }
             }
             // Add empty translations to ensure the locales are "registered" with isAvailable(),
             // and the next invocation of include_by_locale() doesn't cause a new reparse.
             $adapter->addTranslation(array('content' => array($locale => $locale), 'locale' => $locale, 'usetranslateadapter' => true));
         }
     }
 }
 /**
  * Clears the cache for multiple languages.
  *
  * If using the Zend translation module for multiple languages.
  */
 public function flushLanguage()
 {
     // Can only be done if Zend_Translate is loaded.
     if (class_exists('Zend_Translate')) {
         $cache = Zend_Translate::getCache();
         // ...and there is a cache to clear.
         if ($cache) {
             $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
             return 'Successfully cleared';
         }
     }
     return 'No cached data found';
 }