PropertyModifierRegexReplace: w/o match allow null

fixes #2705
This commit is contained in:
Thomas Gelf 2023-02-23 11:44:13 +01:00
parent ce10b7e699
commit 51a7b68803
2 changed files with 30 additions and 13 deletions

View File

@ -19,6 +19,9 @@ This version hasn't been released yet
### Icinga Configuration
* FIX: render Set Services to individual zones where required (#1589, #2356)
### Import and Sync
* FEATURE: regular expression based modifier allows explicit NULL on no match (#2705)
### Configuration Branches
* FEATURE: with this release, directorbranches v1.3 supports a "default branch" (#2688)
* FEATURE: users with default branches get warnings in the main branch (#2689)

View File

@ -9,25 +9,36 @@ class PropertyModifierRegexReplace extends PropertyModifierHook
{
public static function addSettingsFormFields(QuickForm $form)
{
$form->addElement('text', 'pattern', array(
'label' => 'Regex pattern',
$form->addElement('text', 'pattern', [
'label' => $form->translate('Regex pattern'),
'description' => $form->translate(
'The pattern you want to search for. This can be a regular expression like /^www\d+\./'
),
'required' => true,
));
]);
$form->addElement('text', 'replacement', array(
'label' => 'Replacement',
$form->addElement('text', 'replacement', [
'label' => $form->translate('Replacement'),
'description' => $form->translate(
'The string that should be used as a preplacement'
'The string that should be used as a replacement'
),
));
]);
$form->addElement('select', 'when_not_matched', [
'label' => $form->translate('When not matched'),
'description' => $form->translate(
"What should happen, if the given pattern doesn't match"
),
'value' => 'keep',
'multiOptions' => [
'keep' => $form->translate('Keep the given string'),
'set_null' => $form->translate('Set the value to NULL')
]
]);
}
public function getName()
{
return 'Regular expression based replacement';
return mt('director', 'Regular expression based replacement');
}
public function transform($value)
@ -36,10 +47,13 @@ class PropertyModifierRegexReplace extends PropertyModifierHook
return null;
}
return preg_replace(
$this->getSetting('pattern'),
$this->getSetting('replacement'),
$value
);
$result = preg_replace($this->getSetting('pattern'), $this->getSetting('replacement'), $value);
if ($result === $value && $this->getSetting('when_not_matched', 'keep') === 'set_null') {
if (!preg_match($this->getSetting('pattern'), $value)) {
return null;
}
}
return $result;
}
}