refactor formatDate function and create test

This commit is contained in:
Manuel Raynaud
2014-06-17 09:04:59 +02:00
parent 7377af6029
commit f9e0db06c1
3 changed files with 41 additions and 15 deletions

View File

@@ -10,6 +10,8 @@ env:
- DB_USER=root
before_script:
- sudo apt-get update -qq
- sudo apt-get install -y language-pack-fr language-pack-fr-base
- phpenv config-add travis.php.ini
- composer self-update
- composer install --prefer-dist --dev

View File

@@ -89,24 +89,31 @@ class Format extends AbstractSmartyPlugin
$locale = $this->getParam($params,'locale', false);
if($locale === false) {
return $date->format($format);
if (false === $locale) {
$value = $date->format($format);
} else {
if(function_exists('setlocale')) {
// Save the current locale
$system_locale = setlocale('LC_TIME', 0);
setlocale('LC_TIME', $locale);
$localized_date = strftime($format, $date->getTimestamp());
// Restore the locale
setlocale('LC_TIME', $system_locale);
$value = $this->formatDateWithLocale($date, $locale, $format);
}
return $localized_date;
return $value;
}
private function formatDateWithLocale(\DateTime $date, $locale, $format)
{
if (function_exists('setlocale')) {
// Save the current locale
$systemLocale = setlocale('LC_TIME', 0);
setlocale('LC_TIME', $locale);
$localizedDate = strftime($format, $date->getTimestamp());
// Restore the locale
setlocale('LC_TIME', $systemLocale);
return $localizedDate;
} else {
// setlocale() function not available => error
throw new SmartyPluginException("The setlocale() function is not available on your system.");
}
}
}
/**
*

View File

@@ -158,6 +158,23 @@ class FormatTest extends \PHPUnit_Framework_TestCase
$this->assertEmpty($render);
}
public function testFormatDateWithLocale()
{
$dateTime = new \DateTime();
// 2014-06-17
$dateTime->setTimestamp(1402987842);
$formatClass = new Format($this->request);
$render = $formatClass->formatDate(array(
'date' => $dateTime,
'locale' => ['fr_FR.UTF-8', 'fr_FR'],
'format' => '%e %B %Y'
));
$this->assertEquals('17 juin 2014', $render);
}
/**
* test formatNumber without mandatory parameters
*