From b8dbf4abdc4f7e23e89f28dafa0ffd8f2bdcab70 Mon Sep 17 00:00:00 2001 From: Asko Nõmm Date: Mon, 11 Nov 2024 02:10:13 +0200 Subject: Improve testability of FileSystemDriver --- src/Drivers/FileSystemDriver.php | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) (limited to 'src/Drivers/FileSystemDriver.php') diff --git a/src/Drivers/FileSystemDriver.php b/src/Drivers/FileSystemDriver.php index a721b70..6a359aa 100644 --- a/src/Drivers/FileSystemDriver.php +++ b/src/Drivers/FileSystemDriver.php @@ -8,10 +8,10 @@ use DateTime; /** * @author Asko Nõmm */ -readonly class FileSystemDriver implements Driver +class FileSystemDriver implements Driver { public function __construct( - private string $directory, + private readonly string $directory, ) {} /** @@ -35,18 +35,33 @@ readonly class FileSystemDriver implements Driver $path = $this->directory . DIRECTORY_SEPARATOR . $file_name; // If the log file does not exist, try creating one - if (!file_exists($path) && !touch($path)) { + if (!$this->exists($path)) { throw new \RuntimeException('Log file could not be created at path: ' . $path); } // We managed to get this far, but still can't write to the log file - if (!is_writeable($path)) { + if (!$this->isWriteable($path)) { throw new \RuntimeException('Log file is not writeable at path: ' . $path); } + $this->write($path, $serializedMessage . PHP_EOL); + } + + public function exists(string $path): bool + { + return file_exists($path); + } + + public function isWriteable(string $path): bool + { + return is_writeable($path); + } + + public function write(string $path, string $data): void + { file_put_contents( filename: $path, - data: $serializedMessage . PHP_EOL, + data: $data, flags: FILE_APPEND ); } -- cgit v1.2.3