mirror of
https://github.com/kamilwylegala/cakephp2-php8.git
synced 2025-01-31 09:06:17 +00:00
Adds File::replaceText().
Added File::replace() Searches for a given text and replaces the text if found Renamed File::replace() to File::replaceText() Updated the replaceText() method to utilize File Locking Updated File::replaceText() 1. Method now checks if the lock is not identical to null 2. Since the method uses File::read() to get the contents of the file, there is no need for a temporary file. Removed the temporary file creation File::replaceText() update Opening file with r+ mode
This commit is contained in:
parent
26d677f935
commit
98e11cea5d
2 changed files with 49 additions and 0 deletions
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue