Browse Source

Implemented the __dxn() translation function

Jose Lorenzo Rodriguez 11 years ago
parent
commit
3dc052f829
2 changed files with 73 additions and 0 deletions
  1. 31 0
      src/basics.php
  2. 42 0
      tests/TestCase/I18n/I18nTest.php

+ 31 - 0
src/basics.php

@@ -303,3 +303,34 @@ if (!function_exists('__dx')) {
 	}
 
 }
+
+if (!function_exists('__dxn')) {
+
+/**
+ * Returns correct plural form of message identified by $singular and $plural for count $count.
+ * Allows you to override the current domain for a single message lookup.
+ * The context is a unique identifier for the translations string that makes it unique
+ * for in the same domain.
+ *
+ * @param string $domain Domain
+ * @param string $context Context of the text
+ * @param string $singular Singular text to translate
+ * @param string $plural Plural text
+ * @param int $count Count
+ * @param mixed $args Array with arguments or multiple arguments in function
+ * @return mixed plural form of translated string
+ * @link http://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dxn
+ */
+	function __dxn($domain, $context, $singular, $plural, $count, $args = null) {
+		if (!$singular) {
+			return;
+		}
+
+		$arguments = func_num_args() === 6 ? (array)$args : array_slice(func_get_args(), 2);
+		return I18n::translator($domain)->translate(
+			$singular,
+			['_count' => $count, '_singular' => $singular, '_context' => $context] + $arguments
+		);
+	}
+
+}

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

@@ -355,6 +355,48 @@ class I18nTest extends TestCase {
 	}
 
 /**
+ * Tests the __dxn() function
+ *
+ * @return void
+ */
+	public function testDomainPluralContextFunction() {
+		I18n::translator('custom', 'en_US', function () {
+			$package = new Package('default');
+			$package->setMessages([
+				'letter' => [
+					'_context' => [
+						'character' => [
+							'The letter {0}',
+							'The letters {0} and {1}'
+						],
+						'communication' => [
+							'She wrote a letter to {0}',
+							'She wrote a letter to {0} and {1}'
+						]
+					]
+				]
+			]);
+			return $package;
+		});
+		$this->assertEquals(
+			'The letters A and B',
+			__dxn('custom', 'character', 'letter', 'letters', 2, ['A', 'B'])
+		);
+		$this->assertEquals(
+			'The letter A',
+			__dxn('custom', 'character', 'letter', 'letters', 1, ['A']));
+
+		$this->assertEquals(
+			'She wrote a letter to Thomas and Sara',
+			__dxn('custom', 'communication', 'letter', 'letters', 2, ['Thomas', 'Sara'])
+		);
+		$this->assertEquals(
+			'She wrote a letter to Thomas',
+			__dxn('custom', 'communication', 'letter', 'letters', 1, ['Thomas'])
+		);
+	}
+
+/**
  * Tests that translators are cached for performance
  *
  * @return void