diff --git a/src/class-tiny-logger.php b/src/class-tiny-logger.php index 2111d39..6cc2d1a 100644 --- a/src/class-tiny-logger.php +++ b/src/class-tiny-logger.php @@ -108,12 +108,19 @@ public function get_log_file_path() { /** * Triggered when log_enabled is saved * - set the setting on the instance - * - if turn on, clear the old logs + * - will clear logs when turned on + * + * Hooked to `pre_update_option_tinypng_logging_enabled` filter + * + * @return bool true if enabled */ public static function on_save_log_enabled( $log_enabled, $old, $option ) { $instance = self::get_instance(); - $instance->log_enabled = 'on' === $log_enabled; - if ( $instance->get_log_enabled() ) { + $was_enabled = 'on' === $old; + $is_now_enabled = 'on' === $log_enabled; + $instance->log_enabled = $is_now_enabled; + + if ( ! $was_enabled && $is_now_enabled ) { self::clear_logs(); } diff --git a/test/unit/TinyLoggerTest.php b/test/unit/TinyLoggerTest.php index 7140c0e..37721eb 100644 --- a/test/unit/TinyLoggerTest.php +++ b/test/unit/TinyLoggerTest.php @@ -113,4 +113,42 @@ public function test_removes_full_log_and_creates_new() assertTrue(filesize($logger->get_log_file_path()) < 1048576, 'log file rotated and less than 1MB'); } + + public function test_clears_logs_when_turned_on() { + $log_dir_path = 'wp-content/uploads/tiny-compress-logs'; + vfsStream::newDirectory($log_dir_path)->at($this->vfs); + $log_dir = $this->vfs->getChild($log_dir_path); + vfsStream::newFile('tiny-compress.log') + ->withContent('Some existing log content') + ->at($log_dir); + + $logger = Tiny_Logger::get_instance(); + $log_path = $logger->get_log_file_path(); + + assertTrue(file_exists($log_path), 'log file should exist'); + + Tiny_Logger::on_save_log_enabled( 'on', 'off', null ); + + assertFalse( file_exists($log_path), 'log file should be deleted after turning on logging' ); + } + + public function test_keeps_logs_when_unchanged() { + $log_dir_path = 'wp-content/uploads/tiny-compress-logs'; + vfsStream::newDirectory($log_dir_path)->at($this->vfs); + $log_dir = $this->vfs->getChild($log_dir_path); + vfsStream::newFile('tiny-compress.log') + ->withContent('Some existing log content') + ->at($log_dir); + + $logger = Tiny_Logger::get_instance(); + $log_path = $logger->get_log_file_path(); + + assertTrue(file_exists($log_path), 'log file should exist'); + + Tiny_Logger::on_save_log_enabled( 'on', 'on', null ); + + assertTrue( file_exists($log_path), 'log file should still exist when settings remain unchanged' ); + + unlink($log_path); + } }