Skip to content

Commit

Permalink
Making i18n in the validation class optional, closes #5085
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Nov 5, 2014
1 parent fc18336 commit c444da8
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/Validation/Validator.php
Expand Up @@ -50,6 +50,13 @@ class Validator implements \ArrayAccess, \IteratorAggregate, \Countable {
*/
protected $_presenceMessages = [];

/**
* Whether or not to use I18n functions for translating default error messages
*
* @var boolean
*/
protected $_useI18n = false;

/**
* Contains the validation messages associated with checking the emptiness
* for each corresponding field.
Expand All @@ -58,6 +65,14 @@ class Validator implements \ArrayAccess, \IteratorAggregate, \Countable {
*/
protected $_allowEmptyMessages = [];

/**
* Constructor
*
*/
public function __construct() {
$this->_useI18n = function_exists('__d');
}

/**
* Returns an array of fields that have failed validation. On the current model. This method will
* actually run validation rules over data, not just return the messages.
Expand All @@ -69,8 +84,14 @@ class Validator implements \ArrayAccess, \IteratorAggregate, \Countable {
*/
public function errors(array $data, $newRecord = true) {
$errors = [];
$requiredMessage = __d('cake', 'This field is required');
$emptyMessage = __d('cake', 'This field cannot be left empty');

$requiredMessage = 'This field is required';
$emptyMessage = 'This field cannot be left empty';

if ($this->_useI18n) {
$requiredMessage = __d('cake', 'This field is required');
$emptyMessage = __d('cake', 'This field cannot be left empty');
}

foreach ($this->_fields as $name => $field) {
$keyPresent = array_key_exists($name, $data);
Expand Down Expand Up @@ -502,13 +523,19 @@ protected function _processRules($field, ValidationSet $rules, $data, $newRecord
$errors = [];
// Loading default provider in case there is none
$this->provider('default');
$message = 'The provided value is invalid';

if ($this->_useI18n) {
$message = __d('cake', 'The provided value is invalid');
}

foreach ($rules as $name => $rule) {
$result = $rule->process($value, $this->_providers, compact('newRecord', 'data', 'field'));
if ($result === true) {
continue;
}

$errors[$name] = __d('cake', 'The provided value is invalid');
$errors[$name] = $message;
if (is_string($result)) {
$errors[$name] = $result;
}
Expand Down

0 comments on commit c444da8

Please sign in to comment.