|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Copyright MediaCT. All rights reserved. |
|
4
|
|
|
* https://www.mediact.nl |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Mediact\DataContainer; |
|
8
|
|
|
|
|
9
|
|
|
trait ReplaceByPatternTrait |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Get a replacement path for a matched path. |
|
13
|
|
|
* |
|
14
|
|
|
* @param string $pattern |
|
15
|
|
|
* @param string $match |
|
16
|
|
|
* @param string $replacement |
|
17
|
|
|
* @param string $separator |
|
18
|
|
|
* |
|
19
|
|
|
* @return string |
|
20
|
|
|
*/ |
|
21
|
10 |
|
protected function replaceByPattern( |
|
22
|
|
|
string $pattern, |
|
23
|
|
|
string $match, |
|
24
|
|
|
string $replacement, |
|
25
|
|
|
string $separator = DataContainerInterface::SEPARATOR |
|
26
|
|
|
): string { |
|
27
|
10 |
|
return $replacement === '$0' |
|
28
|
1 |
|
? $match |
|
29
|
9 |
|
: $this->replaceByRegex( |
|
30
|
9 |
|
$this->getPatternRegex($pattern, $separator), |
|
31
|
9 |
|
$match, |
|
32
|
10 |
|
$replacement |
|
33
|
|
|
); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Get a replacement path for a matched path by regex. |
|
38
|
|
|
* |
|
39
|
|
|
* @param string $regex |
|
40
|
|
|
* @param string $match |
|
41
|
|
|
* @param string $replacement |
|
42
|
|
|
* |
|
43
|
|
|
* @return string |
|
44
|
|
|
*/ |
|
45
|
9 |
|
private function replaceByRegex( |
|
46
|
|
|
string $regex, |
|
47
|
|
|
string $match, |
|
48
|
|
|
string $replacement |
|
49
|
|
|
): string { |
|
50
|
9 |
|
if (preg_match($regex, $match, $matches)) { |
|
51
|
9 |
|
$replacement = preg_replace_callback( |
|
52
|
9 |
|
'/\$([\d]+)/', |
|
53
|
|
|
function (array $match) use ($matches) { |
|
54
|
9 |
|
return array_key_exists($match[1], $matches) |
|
55
|
9 |
|
? $matches[$match[1]] |
|
56
|
9 |
|
: $match[0]; |
|
57
|
9 |
|
}, |
|
58
|
9 |
|
$replacement |
|
59
|
|
|
); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
9 |
|
return $replacement; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* Translate a fnmatch pattern to a regex. |
|
67
|
|
|
* |
|
68
|
|
|
* @param string $pattern |
|
69
|
|
|
* @param string $separator |
|
70
|
|
|
* |
|
71
|
|
|
* @return string |
|
72
|
|
|
*/ |
|
73
|
9 |
|
private function getPatternRegex( |
|
74
|
|
|
string $pattern, |
|
75
|
|
|
string $separator = DataContainerInterface::SEPARATOR |
|
76
|
|
|
): string { |
|
77
|
|
|
$transforms = [ |
|
78
|
9 |
|
'\*' => sprintf('([^%s]*)', preg_quote($separator, '#')), |
|
79
|
9 |
|
'\?' => '(.)', |
|
80
|
9 |
|
'\[\!' => '([^', |
|
81
|
9 |
|
'\[' => '([', |
|
82
|
9 |
|
'\]' => '])' |
|
83
|
|
|
]; |
|
84
|
|
|
|
|
85
|
9 |
|
$result = sprintf( |
|
86
|
9 |
|
'#^%s$#', |
|
87
|
9 |
|
strtr(preg_quote($pattern, '#'), $transforms) |
|
88
|
|
|
); |
|
89
|
|
|
|
|
90
|
9 |
|
return $result; |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|