blob: 4ab119a9d65102ef9871453e4078714649eefad6 (
plain)
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
|
<?php
namespace Icinga\Module\Director\PropertyModifier;
use Exception;
use gipfl\Json\JsonString;
use Icinga\Exception\InvalidPropertyException;
use Icinga\Module\Director\Hook\PropertyModifierHook;
use Icinga\Module\Director\Web\Form\QuickForm;
class PropertyModifierJsonDecode extends PropertyModifierHook
{
/**
* @param QuickForm $form
* @return QuickForm|void
* @throws \Zend_Form_Exception
*/
public static function addSettingsFormFields(QuickForm $form)
{
$form->addElement('select', 'on_failure', array(
'label' => 'On failure',
'description' => $form->translate(
'What should we do in case we are unable to decode the given string?'
),
'multiOptions' => $form->optionalEnum(array(
'null' => $form->translate('Set no value (null)'),
'keep' => $form->translate('Keep the JSON string as is'),
'fail' => $form->translate('Let the whole import run fail'),
)),
'required' => true,
));
}
public function getName()
{
return 'Decode a JSON string';
}
/**
* @param $value
* @return mixed|null
* @throws InvalidPropertyException|\gipfl\Json\JsonDecodeException
*/
public function transform($value)
{
if (null === $value) {
return null;
}
try {
if (is_string($value)) {
$decoded = JsonString::decode($value);
} else {
throw new InvalidPropertyException(
'JSON decode expects a string, got ' . gettype($value)
);
}
} catch (Exception $e) {
switch ($this->getSetting('on_failure')) {
case 'null':
return null;
case 'keep':
return $value;
case 'fail':
default:
throw $e;
}
}
return $decoded;
}
}
|