diff --git a/lib/Cake/Test/Case/Utility/FileTest.php b/lib/Cake/Test/Case/Utility/FileTest.php index 85a759e00..4a96eef41 100644 --- a/lib/Cake/Test/Case/Utility/FileTest.php +++ b/lib/Cake/Test/Case/Utility/FileTest.php @@ -562,4 +562,26 @@ class FileTest extends CakeTestCase { } return false; } + +/** + * testReplaceText method + * + * @return void + */ + public function testReplaceText() { + $TestFile = new File(__FILE__); + $TmpFile = new File(TMP . 'tests' . DS . 'cakephp.file.test.tmp'); + // Copy the test file to the temporary location + $TestFile->copy($TmpFile->path, true); + + // Replace the contents of the tempory file + $result = $TmpFile->replaceText("* testReplaceText method", "* testReplaceText method passed"); + $this->assertTrue($result); + + // Double check + $contents = $TmpFile->read(); + $this->assertContains("* testReplaceText method passed", $contents); + + $TmpFile->delete(); + } } diff --git a/lib/Cake/Utility/File.php b/lib/Cake/Utility/File.php index 9c1be6afe..1a7c0c815 100644 --- a/lib/Cake/Utility/File.php +++ b/lib/Cake/Utility/File.php @@ -587,4 +587,31 @@ class File { return clearstatcache(); } +/** + * Searches for a given text and replaces the text if found + * @param string $search + * @param string $replace + * @return boolean Success + */ + public function replaceText($search, $replace) { + if (!$this->open("r+")) { + return false; + } + + if ($this->lock !== null) { + if (flock($this->handle, LOCK_EX) === false) { + return false; + } + } + + $replaced = $this->write(str_replace($search, $replace, $this->read()), "w", true); + + if ($this->lock !== null) { + flock($this->handle, LOCK_UN); + } + $this->close(); + + return $replaced; + } + }