Commit cfc57c20 by Carsten Brandt

Allow ITU message format in validator messages

fixes #991
parent 752037d9
...@@ -63,6 +63,9 @@ class I18N extends Component ...@@ -63,6 +63,9 @@ class I18N extends Component
/** /**
* Translates a message to the specified language. * Translates a message to the specified language.
* *
* After translation the message will be parsed using [[MessageFormatter]] if it contains
* ITU message format and `$params` are not empty.
*
* @param string $category the message category. * @param string $category the message category.
* @param string $message the message to be translated. * @param string $message the message to be translated.
* @param array $params the parameters that will be used to replace the corresponding placeholders in the message. * @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
...@@ -102,6 +105,44 @@ class I18N extends Component ...@@ -102,6 +105,44 @@ class I18N extends Component
} }
/** /**
* Formats a message using using [[MessageFormatter]].
*
* @param string $message the message to be formatted.
* @param array $params the parameters that will be used to replace the corresponding placeholders in the message.
* @param string $language the language code (e.g. `en_US`, `en`).
* @return string the formatted message.
*/
public function format($message, $params, $language)
{
$params = (array)$params;
if ($params === []) {
return $message;
}
if (preg_match('~{\s*[\d\w]+\s*,~u', $message)) {
$formatter = new MessageFormatter($language, $message);
if ($formatter === null) {
Yii::warning("Message for $language is invalid: $message.");
return $message;
}
$result = $formatter->format($params);
if ($result === false) {
$errorMessage = $formatter->getErrorMessage();
Yii::warning("Formatting message for $language failed with error: $errorMessage. Message is: $message.");
return $message;
} else {
return $result;
}
}
$p = [];
foreach($params as $name => $value) {
$p['{' . $name . '}'] = $value;
}
return strtr($message, $p);
}
/**
* Returns the message source for the given category. * Returns the message source for the given category.
* @param string $category the category name. * @param string $category the category name.
* @return MessageSource the message source for the given category. * @return MessageSource the message source for the given category.
......
...@@ -58,8 +58,8 @@ class BooleanValidator extends Validator ...@@ -58,8 +58,8 @@ class BooleanValidator extends Validator
$value = $object->$attribute; $value = $object->$attribute;
if (!$this->validateValue($value)) { if (!$this->validateValue($value)) {
$this->addError($object, $attribute, $this->message, [ $this->addError($object, $attribute, $this->message, [
'{true}' => $this->trueValue, 'true' => $this->trueValue,
'{false}' => $this->falseValue, 'false' => $this->falseValue,
]); ]);
} }
} }
......
...@@ -143,8 +143,8 @@ class CompareValidator extends Validator ...@@ -143,8 +143,8 @@ class CompareValidator extends Validator
} }
if (!$valid) { if (!$valid) {
$this->addError($object, $attribute, $this->message, [ $this->addError($object, $attribute, $this->message, [
'{compareAttribute}' => $compareLabel, 'compareAttribute' => $compareLabel,
'{compareValue}' => $compareValue, 'compareValue' => $compareValue,
]); ]);
} }
} }
......
...@@ -144,7 +144,7 @@ class FileValidator extends Validator ...@@ -144,7 +144,7 @@ class FileValidator extends Validator
$this->addError($object, $attribute, $this->uploadRequired); $this->addError($object, $attribute, $this->uploadRequired);
} }
if (count($files) > $this->maxFiles) { if (count($files) > $this->maxFiles) {
$this->addError($object, $attribute, $this->tooMany, ['{attribute}' => $attribute, '{limit}' => $this->maxFiles]); $this->addError($object, $attribute, $this->tooMany, ['limit' => $this->maxFiles]);
} else { } else {
foreach ($files as $file) { foreach ($files as $file) {
$this->validateFile($object, $attribute, $file); $this->validateFile($object, $attribute, $file);
...@@ -171,18 +171,18 @@ class FileValidator extends Validator ...@@ -171,18 +171,18 @@ class FileValidator extends Validator
switch ($file->error) { switch ($file->error) {
case UPLOAD_ERR_OK: case UPLOAD_ERR_OK:
if ($this->maxSize !== null && $file->size > $this->maxSize) { if ($this->maxSize !== null && $file->size > $this->maxSize) {
$this->addError($object, $attribute, $this->tooBig, ['{file}' => $file->name, '{limit}' => $this->getSizeLimit()]); $this->addError($object, $attribute, $this->tooBig, ['file' => $file->name, 'limit' => $this->getSizeLimit()]);
} }
if ($this->minSize !== null && $file->size < $this->minSize) { if ($this->minSize !== null && $file->size < $this->minSize) {
$this->addError($object, $attribute, $this->tooSmall, ['{file}' => $file->name, '{limit}' => $this->minSize]); $this->addError($object, $attribute, $this->tooSmall, ['file' => $file->name, 'limit' => $this->minSize]);
} }
if (!empty($this->types) && !in_array(strtolower(pathinfo($file->name, PATHINFO_EXTENSION)), $this->types, true)) { if (!empty($this->types) && !in_array(strtolower(pathinfo($file->name, PATHINFO_EXTENSION)), $this->types, true)) {
$this->addError($object, $attribute, $this->wrongType, ['{file}' => $file->name, '{extensions}' => implode(', ', $this->types)]); $this->addError($object, $attribute, $this->wrongType, ['file' => $file->name, 'extensions' => implode(', ', $this->types)]);
} }
break; break;
case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_FORM_SIZE:
$this->addError($object, $attribute, $this->tooBig, ['{file}' => $file->name, '{limit}' => $this->getSizeLimit()]); $this->addError($object, $attribute, $this->tooBig, ['file' => $file->name, 'limit' => $this->getSizeLimit()]);
break; break;
case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_PARTIAL:
$this->addError($object, $attribute, $this->message); $this->addError($object, $attribute, $this->message);
......
...@@ -91,10 +91,10 @@ class NumberValidator extends Validator ...@@ -91,10 +91,10 @@ class NumberValidator extends Validator
$this->addError($object, $attribute, $this->message); $this->addError($object, $attribute, $this->message);
} }
if ($this->min !== null && $value < $this->min) { if ($this->min !== null && $value < $this->min) {
$this->addError($object, $attribute, $this->tooSmall, ['{min}' => $this->min]); $this->addError($object, $attribute, $this->tooSmall, ['min' => $this->min]);
} }
if ($this->max !== null && $value > $this->max) { if ($this->max !== null && $value > $this->max) {
$this->addError($object, $attribute, $this->tooBig, ['{max}' => $this->max]); $this->addError($object, $attribute, $this->tooBig, ['max' => $this->max]);
} }
} }
......
...@@ -75,7 +75,7 @@ class RequiredValidator extends Validator ...@@ -75,7 +75,7 @@ class RequiredValidator extends Validator
$this->addError($object, $attribute, $this->message); $this->addError($object, $attribute, $this->message);
} else { } else {
$this->addError($object, $attribute, $this->message, [ $this->addError($object, $attribute, $this->message, [
'{requiredValue}' => $this->requiredValue, 'requiredValue' => $this->requiredValue,
]); ]);
} }
} }
......
...@@ -112,13 +112,13 @@ class StringValidator extends Validator ...@@ -112,13 +112,13 @@ class StringValidator extends Validator
$length = mb_strlen($value, $this->encoding); $length = mb_strlen($value, $this->encoding);
if ($this->min !== null && $length < $this->min) { if ($this->min !== null && $length < $this->min) {
$this->addError($object, $attribute, $this->tooShort, ['{min}' => $this->min]); $this->addError($object, $attribute, $this->tooShort, ['min' => $this->min]);
} }
if ($this->max !== null && $length > $this->max) { if ($this->max !== null && $length > $this->max) {
$this->addError($object, $attribute, $this->tooLong, ['{max}' => $this->max]); $this->addError($object, $attribute, $this->tooLong, ['max' => $this->max]);
} }
if ($this->length !== null && $length !== $this->length) { if ($this->length !== null && $length !== $this->length) {
$this->addError($object, $attribute, $this->notEqual, ['{length}' => $this->length]); $this->addError($object, $attribute, $this->notEqual, ['length' => $this->length]);
} }
} }
......
...@@ -251,9 +251,9 @@ abstract class Validator extends Component ...@@ -251,9 +251,9 @@ abstract class Validator extends Component
public function addError($object, $attribute, $message, $params = []) public function addError($object, $attribute, $message, $params = [])
{ {
$value = $object->$attribute; $value = $object->$attribute;
$params['{attribute}'] = $object->getAttributeLabel($attribute); $params['attribute'] = $object->getAttributeLabel($attribute);
$params['{value}'] = is_array($value) ? 'array()' : $value; $params['value'] = is_array($value) ? 'array()' : $value;
$object->addError($attribute, strtr($message, $params)); $object->addError($attribute, Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
} }
/** /**
......
...@@ -220,7 +220,7 @@ class ValidatorTest extends TestCase ...@@ -220,7 +220,7 @@ class ValidatorTest extends TestCase
$errors = $m->getErrors('attr_msg_val'); $errors = $m->getErrors('attr_msg_val');
$this->assertEquals('attr_msg_val::array()', $errors[0]); $this->assertEquals('attr_msg_val::array()', $errors[0]);
$m = $this->getTestModel(['attr_msg_val' => 'abc']); $m = $this->getTestModel(['attr_msg_val' => 'abc']);
$val->addError($m, 'attr_msg_val', '{attribute}::{value}::{param}', ['{param}' => 'param_value']); $val->addError($m, 'attr_msg_val', '{attribute}::{value}::{param}', ['param' => 'param_value']);
$errors = $m->getErrors('attr_msg_val'); $errors = $m->getErrors('attr_msg_val');
$this->assertEquals('attr_msg_val::abc::param_value', $errors[0]); $this->assertEquals('attr_msg_val::abc::param_value', $errors[0]);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment