mirror of
https://github.com/kamilwylegala/cakephp2-php8.git
synced 2025-01-19 02:56:15 +00:00
Merge pull request #1665 from rooseveltrp/2.5
Added a method File::replace() to the File Utilities.
This commit is contained in:
commit
03b0f40e9d
2 changed files with 64 additions and 0 deletions
|
@ -562,4 +562,40 @@ class FileTest extends CakeTestCase {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* testReplaceText method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function testReplaceText() {
|
||||
$TestFile = new File(dirname(__FILE__) . '/../../test_app/Vendor/welcome.php');
|
||||
$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('welcome.php', 'welcome.tmp');
|
||||
$this->assertTrue($result);
|
||||
|
||||
// Double check
|
||||
$expected = 'This is the welcome.tmp file in vendors directory';
|
||||
$contents = $TmpFile->read();
|
||||
$this->assertContains($expected, $contents);
|
||||
|
||||
$search = array('This is the', 'welcome.php file', 'in tmp directory');
|
||||
$replace = array('This should be a', 'welcome.tmp file', 'in the Lib directory');
|
||||
|
||||
// Replace the contents of the tempory file
|
||||
$result = $TmpFile->replaceText($search, $replace);
|
||||
$this->assertTrue($result);
|
||||
|
||||
// Double check
|
||||
$expected = 'This should be a welcome.tmp file in vendors directory';
|
||||
$contents = $TmpFile->read();
|
||||
$this->assertContains($expected, $contents);
|
||||
|
||||
$TmpFile->delete();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -587,4 +587,32 @@ class File {
|
|||
return clearstatcache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for a given text and replaces the text if found.
|
||||
*
|
||||
* @param string|array $search Text(s) to search for.
|
||||
* @param string|array $replace Text(s) to replace with.
|
||||
* @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