Fix Icinga\web\Hook

refs #4301
This commit is contained in:
Eric Lippmann 2013-06-28 11:16:35 +02:00
parent 9d0d11418a
commit a90a19eb60
1 changed files with 94 additions and 1 deletions

View File

@ -39,6 +39,19 @@ class Hook
*/
protected static $instances = array();
/**
* @var string
*/
public static $BASE_NS = 'Icinga\\Web\\Hook\\';
public static function clean()
{
self::$hooks = array();
self::$instances = array();
self::$BASE_NS = 'Icinga\\Web\\Hook\\';
}
/**
* Whether someone registered itself for the given hook name
*
@ -97,6 +110,86 @@ class Hook
return self::$instances[$name];
}
/**
* Create or return an instance of the hook
* @param string $name
* @param string $key
* @return \stdClass
*/
public static function createInstance($name, $key)
{
if (!self::has($name, $key)) {
return null;
}
if (isset(self::$instances[$name][$key])) {
return self::$instances[$name][$key];
}
$class = self::$hooks[$name][$key];
try {
$instance = new $class();
} catch (\Exception $e) {
Log::debug(
'Hook "%s" (%s) (%s) failed, will be unloaded: %s',
$name,
$key,
$class,
$e->getMessage()
);
unset(self::$hooks[$name][$key]);
return null;
}
self::assertValidHook($instance, $name);
self::$instances[$name][$key] = $instance;
return $instance;
}
/**
* Test for a valid class name
* @param \stdClass $instance
* @param string $name
* @throws \Icinga\Exception\ProgrammingError
*/
private static function assertValidHook(&$instance, $name)
{
$base_class = self::$BASE_NS . ucfirst($name);
if (!$instance instanceof $base_class) {
throw new ProgrammingError(
sprintf(
'%s is not an instance of %s',
get_class($instance),
$base_class
)
);
}
}
/**
* Return all instances of a specific name
* @param string $name
* @return array
*/
public static function all($name)
{
if (!self::has($name)) {
return array();
}
foreach (self::$hooks[$name] as $key => $hook) {
if (self::createInstance($name, $key) === null) {
return array();
}
}
return self::$instances[$name];
}
/**
* @param string $name
* @return \stdClass
*/
public static function first($name)
{
return self::createInstance($name, key(self::$hooks[$name]));
}
/**
* Register your hook
*
@ -108,7 +201,7 @@ class Hook
*
* @return void
*/
public static function register($name, $class)
public static function register($name, $key, $class)
{
self::registerClass($name, $key, $class);
}