Refactor file locking to return status and handle failure.

This commit is contained in:
netkas 2025-01-09 15:42:44 -05:00
parent 808baec53c
commit 0507fbb9d1
2 changed files with 13 additions and 4 deletions
CHANGELOG.md
src/LogLib/Classes

View file

@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
This update introduces a minor bug fix
### Fixed
- Refactor file locking to return status and handle failure.
## [2.0.4] - 2024-12-04

View file

@ -42,12 +42,12 @@
*
* @throws RuntimeException if unable to open or lock the file.
*/
private function lock(): void
private function lock(): bool
{
$this->fileHandle = fopen($this->filePath, 'a');
$this->fileHandle = @fopen($this->filePath, 'a');
if ($this->fileHandle === false)
{
throw new RuntimeException("Unable to open the file: " . $this->filePath);
return false;
}
// Keep trying to acquire the lock until it succeeds
@ -64,6 +64,8 @@
flock($this->fileHandle, LOCK_UN);
$this->lock();
}
return true;
}
/**
@ -87,7 +89,11 @@
*/
public function append(string $data): void
{
$this->lock();
if(!$this->lock())
{
// Do not proceed if the file cannot be locked
return;
}
if ($this->fileHandle !== false)
{