1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the humbug/php-scoper package. |
7
|
|
|
* |
8
|
|
|
* Copyright (c) 2017 Théo FIDRY <[email protected]>, |
9
|
|
|
* Pádraic Brady <[email protected]> |
10
|
|
|
* |
11
|
|
|
* For the full copyright and license information, please view the LICENSE |
12
|
|
|
* file that was distributed with this source code. |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace Humbug\PhpScoper\Scoper; |
16
|
|
|
|
17
|
|
|
use Humbug\PhpScoper\Scoper; |
18
|
|
|
use Humbug\PhpScoper\Throwable\Exception\RuntimeException; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @final |
22
|
|
|
*/ |
23
|
|
|
class StringReplacer implements Scoper |
24
|
|
|
{ |
25
|
|
|
private $replaceMap = []; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var Scoper |
29
|
|
|
*/ |
30
|
|
|
private $decoratedScoper; |
31
|
|
|
|
32
|
|
|
public function __construct(Scoper $decoratedScoper) |
33
|
|
|
{ |
34
|
|
|
$this->decoratedScoper = $decoratedScoper; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function configureReplaceMap(array $replaceMap) |
38
|
|
|
{ |
39
|
|
|
$this->replaceMap = $this->mapByFile($replaceMap); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Replaces selected strings in files if configured by user. |
44
|
|
|
* |
45
|
|
|
* {@inheritdoc} |
46
|
|
|
*/ |
47
|
|
|
public function scope(string $filePath, string $prefix): string |
48
|
|
|
{ |
49
|
|
|
$content = $this->decoratedScoper->scope($filePath, $prefix); |
50
|
|
|
|
51
|
|
|
if (!isset($this->replaceMap[$filePath])) { |
52
|
|
|
|
53
|
|
|
return $content; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
foreach ($this->replaceMap[$filePath] as $replacement) { |
57
|
|
|
$content = preg_replace( |
58
|
|
|
$replacement['pattern'], |
59
|
|
|
$replacement['replacement'], |
60
|
|
|
$content, |
61
|
|
|
-1, |
62
|
|
|
$count |
63
|
|
|
); |
64
|
|
|
|
65
|
|
|
if (0 === $count) { |
66
|
|
|
throw new RuntimeException( |
67
|
|
|
sprintf( |
68
|
|
|
'The following string replacement could not be applied:'.PHP_EOL |
69
|
|
|
.'File: %s'.PHP_EOL |
70
|
|
|
.'Pattern: %s'.PHP_EOL |
71
|
|
|
.'Replacement: %s', |
72
|
|
|
$filePath, |
73
|
|
|
$replacement['pattern'], |
74
|
|
|
$replacement['replacement'] |
75
|
|
|
) |
76
|
|
|
); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $content; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
private function mapByFile(array $replaceMap): array |
84
|
|
|
{ |
85
|
|
|
$map = []; |
86
|
|
|
foreach ($replaceMap as $replace) { |
87
|
|
|
foreach ($replace['files'] as $file) { |
88
|
|
|
$map[$file][] = [ |
89
|
|
|
'pattern' => $replace['pattern'], |
90
|
|
|
'replacement' => $replace['replacement'], |
91
|
|
|
]; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
return $map; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|