forked from Smile-SA/gdpr-dump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegexReplace.php
66 lines (54 loc) · 1.64 KB
/
RegexReplace.php
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
<?php
declare(strict_types=1);
namespace Smile\GdprDump\Converter\Transformer;
use RuntimeException;
use Smile\GdprDump\Converter\ConverterInterface;
use Smile\GdprDump\Converter\Parameters\Parameter;
use Smile\GdprDump\Converter\Parameters\ParameterProcessor;
use Smile\GdprDump\Converter\Parameters\ValidationException;
class RegexReplace implements ConverterInterface
{
/**
* @var string
*/
private $pattern;
/**
* @var string
*/
private $replacement;
/**
* @var int
*/
private $limit;
/**
* @param array $parameters
* @throws ValidationException
*/
public function __construct(array $parameters)
{
$input = (new ParameterProcessor())
->addParameter('pattern', Parameter::TYPE_STRING, true)
->addParameter('replacement', Parameter::TYPE_STRING, false, '')
->addParameter('limit', Parameter::TYPE_INT, true, -1)
->process($parameters);
$this->pattern = $input->get('pattern');
$this->replacement = $input->get('replacement');
$this->limit = $input->get('limit');
}
/**
* @inheritdoc
*/
public function convert($value, array $context = [])
{
$value = (string) $value;
if ($value !== '') {
$value = preg_replace($this->pattern, $this->replacement, (string) $value, $this->limit);
if ($value === null) {
throw new RuntimeException(
sprintf('Failed to perform a regex search and replace with the pattern "%s".', $this->pattern)
);
}
}
return $value;
}
}