|
5 | 5 | namespace TypistTech\Imposter; |
6 | 6 |
|
7 | 7 | use SplFileInfo; |
| 8 | +use TRegx\CleanRegex\Match\Details\Match; |
8 | 9 |
|
9 | 10 | class Transformer implements TransformerInterface |
10 | 11 | { |
@@ -155,12 +156,29 @@ private function prefixUseFunction(string $targetFile) |
155 | 156 | private function prefixUse(string $targetFile) |
156 | 157 | { |
157 | 158 | $pattern = sprintf( |
158 | | - '/%1$s\\s+(?!(const)|(function)|(%2$s)|(\\\\(?!.*\\\\.*))|(Composer(\\\\|;)|(?!.*\\\\.*)))/', |
| 159 | + '%1$s\\s+(?!(const)|(function)|(%2$s)|(\\\\(?!.*\\\\.*))|(Composer(\\\\|;)|(?!.*\\\\.*)))', |
159 | 160 | 'use', |
160 | 161 | $this->namespacePrefix |
161 | 162 | ); |
162 | | - $replacement = sprintf('%1$s %2$s', 'use', $this->namespacePrefix); |
163 | | - |
164 | | - $this->replace($pattern, $replacement, $targetFile); |
| 163 | + $replacement = sprintf('%1$s %2$s', 'use', str_replace('\\\\', '\\', $this->namespacePrefix)); |
| 164 | + |
| 165 | + $content = $this->filesystem->get($targetFile); |
| 166 | + $output = pattern($pattern)->replace($content)->all() |
| 167 | + ->callback(function (Match $m) use ($replacement, $content) { |
| 168 | + // Find previous offset content and check if the last match of namespace or class is "class" |
| 169 | + $offsetContent = substr($content, 0, $m->offset()); |
| 170 | + preg_match_all( |
| 171 | + '/(namespace|class)[A-Za-z0-9\\\\ ]+.?{/sm', |
| 172 | + $offsetContent, |
| 173 | + $nsClass, |
| 174 | + PREG_SET_ORDER |
| 175 | + ); |
| 176 | + if (count($nsClass) > 0 && $nsClass[count($nsClass) - 1][1] === 'class') { |
| 177 | + return $m->text(); |
| 178 | + } |
| 179 | + return $replacement; |
| 180 | + }); |
| 181 | + |
| 182 | + $this->filesystem->put($targetFile, $output); |
165 | 183 | } |
166 | 184 | } |
0 commit comments