1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
<?php
/* Icinga DB Web | (c) 2021 Icinga GmbH | GPLv2 */
namespace Icinga\Module\Icingadb\Hook;
use Closure;
use Exception;
use Icinga\Application\Hook;
use Icinga\Application\Logger;
use Icinga\Module\Icingadb\Hook\Common\HookUtils;
use ipl\Orm\Model;
abstract class CustomVarRendererHook
{
use HookUtils;
/**
* Prefetch the data the hook needs to render custom variables
*
* @param Model $object The object for which they'll be rendered
*
* @return bool Return true if the hook can render variables for the given object, false otherwise
*/
abstract public function prefetchForObject(Model $object): bool;
/**
* Render the given variable name
*
* @param string $key
*
* @return ?mixed
*/
abstract public function renderCustomVarKey(string $key);
/**
* Render the given variable value
*
* @param string $key
* @param mixed $value
*
* @return ?mixed
*/
abstract public function renderCustomVarValue(string $key, $value);
/**
* Return a group name for the given variable name
*
* @param string $key
*
* @return ?string
*/
abstract public function identifyCustomVarGroup(string $key): ?string;
/**
* Prepare available hooks to render custom variables of the given object
*
* @param Model $object
*
* @return Closure A callback ($key, $value) which returns an array [$newKey, $newValue, $group]
*/
final public static function prepareForObject(Model $object): Closure
{
$hooks = [];
foreach (Hook::all('Icingadb/CustomVarRenderer') as $hook) {
/** @var self $hook */
try {
if ($hook->prefetchForObject($object)) {
$hooks[] = $hook;
}
} catch (Exception $e) {
Logger::error('Failed to load hook %s:', get_class($hook), $e);
}
}
return function (string $key, $value) use ($hooks) {
$newKey = $key;
$newValue = $value;
$group = null;
foreach ($hooks as $hook) {
/** @var self $hook */
try {
$renderedKey = $hook->renderCustomVarKey($key);
$renderedValue = $hook->renderCustomVarValue($key, $value);
$group = $hook->identifyCustomVarGroup($key);
} catch (Exception $e) {
Logger::error('Failed to use hook %s:', get_class($hook), $e);
continue;
}
if ($renderedKey !== null || $renderedValue !== null) {
$newKey = $renderedKey ?? $key;
$newValue = $renderedValue ?? $value;
break;
}
}
return [$newKey, $newValue, $group];
};
}
}
|