cerbero90 /
console-tasker
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Cerbero\ConsoleTasker\Traits; |
||
| 4 | |||
| 5 | /** |
||
| 6 | * The trait to manipulate files by adding new stubs. |
||
| 7 | * |
||
| 8 | */ |
||
| 9 | trait AddsStubs |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * Add the given stub before the last occurrence of the searched text |
||
| 13 | * |
||
| 14 | * @param string $search |
||
| 15 | * @param string $path |
||
| 16 | * @param array $replacements |
||
| 17 | * @return self |
||
| 18 | */ |
||
| 19 | public function addStubBeforeLast(string $search, string $path, array $replacements = []): self |
||
| 20 | { |
||
| 21 | $regex = "/{$search}(?!.*{$search})/s"; |
||
| 22 | |||
| 23 | return $this->addStubBeforeRegex($regex, $path, $replacements); |
||
| 24 | } |
||
| 25 | |||
| 26 | /** |
||
| 27 | * Add the given stub before the provided regular expression |
||
| 28 | * |
||
| 29 | * @param string $regex |
||
| 30 | * @param string $path |
||
| 31 | * @param array $replacements |
||
| 32 | * @return self |
||
| 33 | */ |
||
| 34 | public function addStubBeforeRegex(string $regex, string $path, array $replacements = []): self |
||
| 35 | { |
||
| 36 | return $this->addStubByRegex($regex, $path, $replacements, function ($stubContent, $matches) { |
||
| 37 | return $stubContent . $matches[0]; |
||
| 38 | }); |
||
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * Add the given stub based on the provided regular expression |
||
| 43 | * |
||
| 44 | * @param string $regex |
||
| 45 | * @param string $path |
||
| 46 | * @param array $replacements |
||
| 47 | * @param callable $callable |
||
| 48 | * @return self |
||
| 49 | */ |
||
| 50 | public function addStubByRegex(string $regex, string $path, array $replacements, callable $callable): self |
||
| 51 | { |
||
| 52 | $stubContent = str_replace(array_keys($replacements), array_values($replacements), file_get_contents($path)); |
||
| 53 | |||
| 54 | $callback = function (array $matches) use ($callable, $stubContent) { |
||
| 55 | return $callable($stubContent, $matches); |
||
| 56 | }; |
||
| 57 | |||
| 58 | $content = preg_replace_callback($regex, $callback, file_get_contents($this->getPath())); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 59 | |||
| 60 | file_put_contents($this->getPath(), $content); |
||
| 61 | |||
| 62 | return $this; |
||
| 63 | } |
||
| 64 | } |
||
| 65 |