Skip to content

Commit

Permalink
[8.x] Add Filesystem::replaceInFile method (#38069)
Browse files Browse the repository at this point in the history
* feature: introduce Filesystem::replaceInFile method

* tests: Filesystem::replaceInFile

* chore: keep params types inline with str_replace
  • Loading branch information
ryangjchandler authored Jul 20, 2021
1 parent a32780c commit aca553a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Filesystem/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,19 @@ public function replace($path, $content)
rename($tempPath, $path);
}

/**
* Replace a given string within a given file.
*
* @param array|string $search
* @param array|string $replace
* @param string $path
* @return void
*/
public function replaceInFile($search, $replace, $path)
{
file_put_contents($path, str_replace($search, $replace, file_get_contents($path)));
}

/**
* Prepend to a file.
*
Expand Down
11 changes: 11 additions & 0 deletions tests/Filesystem/FilesystemTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ public function testReplaceCreatesFile()
$this->assertStringEqualsFile($tempFile, 'Hello World');
}

public function testReplaceInFileCorrectlyReplaces()
{
$tempFile = self::$tempDir.'/file.txt';

$filesystem = new Filesystem;

$filesystem->put($tempFile, 'Hello World');
$filesystem->replaceInFile('Hello World', 'Hello Taylor', $tempFile);
$this->assertStringEqualsFile($tempFile, 'Hello Taylor');
}

public function testReplaceWhenUnixSymlinkExists()
{
if (windows_os()) {
Expand Down

0 comments on commit aca553a

Please sign in to comment.