Browse Source

Adding I18n::factory() to register generic translator loaders

Jose Lorenzo Rodriguez 11 years ago
parent
commit
702cd951ab
2 changed files with 58 additions and 0 deletions
  1. 12 0
      src/I18n/I18n.php
  2. 46 0
      tests/TestCase/I18n/I18nTest.php

+ 12 - 0
src/I18n/I18n.php

@@ -139,6 +139,18 @@ class I18n {
 	}
 
 /**
+ *
+ *
+ * @param string $locale The name of translator to create a loader for
+ * @param callable $looader A callable object that should return a Package
+ * instance to be used for assembling a new translator.
+ * @return void
+ */
+	public static function factory($name, callable $loader) {
+		static::translators()->registerLoader($name, $loader);
+	}
+
+/**
  * Sets the default locale to use for future translator instances.
  * This also affects the `intl.default_locale` php setting.
  *

+ 46 - 0
tests/TestCase/I18n/I18nTest.php

@@ -301,4 +301,50 @@ class I18nTest extends TestCase {
 		$this->assertSame($spanish, I18n::translator('default', 'es_ES'));
 	}
 
+/**
+ * Tests that it is possible to register a generic translators factory for a domain
+ * instad of having to create them manually
+ *
+ * @return void
+ */
+	public function testloaderFactory() {
+		I18n::factory('custom', function($name, $locale) {
+			$this->assertEquals('custom', $name);
+			$package = new Package('default');
+
+			if ($locale == 'fr_FR') {
+				$package->setMessages([
+				'Cow' => 'Le Moo',
+				'Cows' => [
+					'Le Moo',
+					'Les Moos'
+					]
+				]);
+			}
+			
+			if ($locale === 'es_ES') {
+				$package->setMessages([
+				'Cow' => 'El Moo',
+				'Cows' => [
+					'El Moo',
+					'Los Moos'
+					]
+				]);
+			}
+
+			return $package;
+		});
+
+		$translator = I18n::translator('custom', 'fr_FR');
+		$this->assertEquals('Le Moo', $translator->translate('Cow'));
+		$this->assertEquals('Les Moos', $translator->translate('Cows', ['_count' => 2]));
+
+		$translator = I18n::translator('custom', 'es_ES');
+		$this->assertEquals('El Moo', $translator->translate('Cow'));
+		$this->assertEquals('Los Moos', $translator->translate('Cows', ['_count' => 2]));
+
+		$translator = I18n::translator();
+		$this->assertEquals('%d is 1 (po translated)', $translator->translate('%d = 1'));
+	}
+
 }