Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add Filesystem::replaceInFile method #38069

Merged
merged 3 commits into from
Jul 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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