Browse Source

Implemented __dx() function

Jose Lorenzo Rodriguez 11 years ago
parent
commit
c51bf58fd1
2 changed files with 54 additions and 0 deletions
  1. 28 0
      src/basics.php
  2. 26 0
      tests/TestCase/I18n/I18nTest.php

+ 28 - 0
src/basics.php

@@ -275,3 +275,31 @@ if (!function_exists('__xn')) {
 	}
 
 }
+
+if (!function_exists('__dx')) {
+
+/**
+ * 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 $msg String to translate
+ * @param mixed $args Array with arguments or multiple arguments in function
+ * @return string translated string
+ * @link http://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dx
+ */
+	function __dx($domain, $context, $msg, $args = null) {
+		if (!$msg) {
+			return;
+		}
+
+		$arguments = func_num_args() === 4 ? (array)$args : array_slice(func_get_args(), 2);
+		return I18n::translator($domain)->translate(
+			$msg,
+			['_context' => $context] + $arguments
+		);
+	}
+
+}

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

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