From 0507fbb9d109519034eb6f9b8b9a23c544aaa84b Mon Sep 17 00:00:00 2001 From: netkas Date: Thu, 9 Jan 2025 15:42:44 -0500 Subject: [PATCH] Refactor file locking to return status and handle failure. --- CHANGELOG.md | 3 +++ src/LogLib/Classes/FileLock.php | 14 ++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e92530f..bfc10d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/LogLib/Classes/FileLock.php b/src/LogLib/Classes/FileLock.php index c8c5031..692cf24 100644 --- a/src/LogLib/Classes/FileLock.php +++ b/src/LogLib/Classes/FileLock.php @@ -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) {