Framework: Implement time zone aware DateTimeFactory

refs #4440
This commit is contained in:
Eric Lippmann 2013-08-12 10:54:16 +02:00
parent 3d104474d9
commit b4b51b9d46
3 changed files with 71 additions and 4 deletions

View File

@ -30,11 +30,12 @@ namespace Icinga\Application;
use \DateTimeZone;
use \Exception;
use Zend_Loader_Autoloader;
use Icinga\Application\Modules\Manager as ModuleManager;
use Icinga\Application\Platform;
use \Icinga\Application\Config;
use Icinga\Exception\ConfigurationError;
use Zend_Loader_Autoloader;
use Icinga\Util\DateTimeFactory;
/**
* This class bootstraps a thin Icinga application layer
@ -340,20 +341,21 @@ abstract class ApplicationBootstrap
}
/**
* Setup timezone
* Setup time zone
*
* @return self
* @throws \Icinga\Exception\ConfigurationError if the timezone in config.ini isn't valid
* @throws ConfigurationError if the timezone in config.ini isn't valid
*/
protected function setupTimezone()
{
$tz = $this->config->global->get('timezone', 'UTC');
try {
new DateTimeZone($tz);
$tz = new DateTimeZone($tz);
} catch (Exception $e) {
throw new ConfigurationError(t('Invalid timezone') . ' "' . $tz . '"');
}
date_default_timezone_set($tz);
DateTimeFactory::setConfig(array('timezone' => $tz));
return $this;
}
}

View File

@ -0,0 +1,19 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Util;
/**
* Interface defining a factory which is configured at runtime
*/
interface ConfigAwareFactory
{
/**
* Set the factory's config
*
* @param mixed $config
* @throws \Icinga\Exception\ConfigurationError if the given config is not valid
*/
public static function setConfig($config);
}

View File

@ -0,0 +1,46 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Util;
use \DateTime;
use \DateTimeZone;
use Icinga\Util\ConfigAwareFactory;
use Icinga\Exception\ConfigurationError;
class DateTimeFactory implements ConfigAwareFactory
{
private static $timeZone;
/**
* Set the factory's config
*
* Set the factory's time zone via key timezone in the given config array
*
* @param array $config
* @throws \Icinga\Exception\ConfigurationError if the given config is not valid
*/
public static function setConfig($config)
{
if (!array_key_exists('timezome', $config)) {
throw new ConfigurationError(t('"DateTimeFactory" expects a valid time zone to be set via "setConfig"'));
}
self::$timeZone = $config['timezone'];
}
/**
* Return new DateTime object using the set time zone
*
* Wraps DateTime::__construct()
*
* @param string $time
* @param DateTimeZone $timeZone
* @return DateTime
* @see DateTime::__construct()
*/
public static function create($time = 'now', DateTimeZone $timeZone = null)
{
return new DateTime($time, $timeZone !== null ? $timeZone : self::$timeZone);
}
}