Skip to content

Commit

Permalink
Decimal validate based on Intl not setlocale
Browse files Browse the repository at this point in the history
Refs #5876
  • Loading branch information
CauanCabral committed Feb 25, 2015
1 parent 3490cd6 commit 4d93f7f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
10 changes: 7 additions & 3 deletions src/Validation/Validation.php
Expand Up @@ -479,9 +479,13 @@ public static function decimal($check, $places = null, $regex = null)
}

// account for localized floats.
$data = localeconv();
$check = str_replace($data['thousands_sep'], '', $check);
$check = str_replace($data['decimal_point'], '.', $check);
$locale = ini_get('intl.default_locale') ?: 'en_US';
$formatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
$decimalPoint = $formatter->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL);
$groupingSep = $formatter->getSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL);

$check = str_replace($groupingSep, '', $check);
$check = str_replace($decimalPoint, '.', $check);

return static::_check($check, $regex);
}
Expand Down
17 changes: 5 additions & 12 deletions tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -20,6 +20,7 @@
use Cake\Filesystem\File;
use Cake\TestSuite\TestCase;
use Cake\Validation\Validation;
use Locale;

/**
* CustomValidator class
Expand Down Expand Up @@ -56,11 +57,8 @@ public function setUp()
{
parent::setUp();
$this->_appEncoding = Configure::read('App.encoding');
$this->_appLocale = [];
foreach ([LC_MONETARY, LC_NUMERIC, LC_TIME] as $category) {
$this->_appLocale[$category] = setlocale($category, 0);
setlocale($category, 'en_US');
}
$this->locale = Locale::getDefault();
Locale::setDefault('en_US');
}

/**
Expand All @@ -72,9 +70,7 @@ public function tearDown()
{
parent::tearDown();
Configure::write('App.encoding', $this->_appEncoding);
foreach ($this->_appLocale as $category => $locale) {
setlocale($category, $locale);
}
Locale::setDefault($this->locale);
}

/**
Expand Down Expand Up @@ -1751,16 +1747,13 @@ public function testDecimalCustomRegex()
public function testDecimalLocaleSet()
{
$this->skipIf(DS === '\\', 'The locale is not supported in Windows and affects other tests.');
$restore = setlocale(LC_NUMERIC, 0);
$this->skipIf(setlocale(LC_NUMERIC, 'da_DK') === false, "The Danish locale isn't available.");
$this->skipIf(Locale::setDefault('da_DK') === false, "The Danish locale isn't available.");

$this->assertTrue(Validation::decimal(1.54), '1.54 should be considered a valid float');
$this->assertTrue(Validation::decimal('1.54'), '"1.54" should be considered a valid float');

$this->assertTrue(Validation::decimal(12345.67), '12345.67 should be considered a valid float');
$this->assertTrue(Validation::decimal('12,345.67'), '"12,345.67" should be considered a valid float');

setlocale(LC_NUMERIC, $restore);
}

/**
Expand Down

0 comments on commit 4d93f7f

Please sign in to comment.