1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* inetprocess/transformation |
4
|
|
|
* |
5
|
|
|
* PHP Version 5.3 |
6
|
|
|
* |
7
|
|
|
* @author Emmanuel Dyan |
8
|
|
|
* @copyright 2005-2015 iNet Process |
9
|
|
|
* |
10
|
|
|
* @package inetprocess/transformation |
11
|
|
|
* |
12
|
|
|
* @license GNU General Public License v2.0 |
13
|
|
|
* |
14
|
|
|
* @link http://www.inetprocess.com |
15
|
|
|
*/ |
16
|
|
|
|
17
|
|
|
namespace Inet\Transformation\Rule; |
18
|
|
|
|
19
|
|
|
use Inet\Transformation\Exception\TransformationException; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Replace a string with a Regexp |
23
|
|
|
*/ |
24
|
|
|
class ReplaceRegexp extends AbstractRule |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* PHP Constants that says what's happened with the PregRegexp |
28
|
|
|
* |
29
|
|
|
* @var array |
30
|
|
|
*/ |
31
|
|
|
protected $pregErrs = array( |
32
|
|
|
\PREG_INTERNAL_ERROR => 'Internal Error', |
33
|
|
|
\PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit', |
34
|
|
|
\PREG_RECURSION_LIMIT_ERROR => 'Recursion limit', |
35
|
|
|
\PREG_BAD_UTF8_ERROR => 'Bad UTF-8', |
36
|
|
|
\PREG_BAD_UTF8_OFFSET_ERROR => 'Bad UTF-8 Offset' |
37
|
|
|
); |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Operate the transformation |
41
|
|
|
* |
42
|
|
|
* @param string $input |
43
|
|
|
* @param array $arguments |
44
|
|
|
* |
45
|
|
|
* @throws Inet\Transformation\Exception\TransformationException |
46
|
|
|
* |
47
|
|
|
* @return string |
48
|
|
|
*/ |
49
|
5 |
|
public function transform($input, array $arguments) |
50
|
|
|
{ |
51
|
|
|
// I should have two arguments: old format / new format |
52
|
5 |
|
if (count($arguments) !== 2) { |
53
|
2 |
|
throw new TransformationException('Rule ReplaceRegexp Expects exactly 2 arguments'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
// Validate That the regexp was OK |
57
|
3 |
|
$output = preg_replace($arguments[0], $arguments[1], $input); |
58
|
3 |
|
if (is_null($output)) { |
59
|
1 |
|
$pregErr = preg_last_error(); |
60
|
1 |
|
$pregMsg = array_key_exists($pregErr, $this->pregErrs) ? $this->pregErrs[$pregErr] : 'Unknown error'; |
61
|
1 |
|
$msg = 'ReplaceRegexp was not able to transform your string: '.$pregMsg; |
62
|
1 |
|
throw new TransformationException($msg); |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
return $output; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|