From ac6cb56d56b775a16047a73d641f4b2c3f3fd0d6 Mon Sep 17 00:00:00 2001 From: Stefan Kalscheuer Date: Thu, 8 Sep 2022 16:57:02 +0200 Subject: [PATCH] add "statify__skip_aggregation" hook to disable aggregation If Statify is extended by custom columns the aggregation routine will fail. To support such scenarios, we introduce a boolean hook, so the previous behavior can be preserved without breaking compatibility. --- inc/class-statify-cron.php | 15 +++++++-------- tests/test-cron.php | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/inc/class-statify-cron.php b/inc/class-statify-cron.php index 3184869..7af0b93 100644 --- a/inc/class-statify-cron.php +++ b/inc/class-statify-cron.php @@ -23,13 +23,12 @@ class Statify_Cron extends Statify { * * @since 0.3.0 * @version 1.4.0 + * @wp-hook boolean statify__skip_aggregation */ public static function cleanup_data() { - - // Global. global $wpdb; - // Remove items. + // Remove old items. $wpdb->query( $wpdb->prepare( "DELETE FROM `$wpdb->statify` WHERE created <= SUBDATE(%s, %d)", @@ -38,13 +37,13 @@ public static function cleanup_data() { ) ); - // Aggregate. - self::aggregate_data(); + // Aggregate data. + if ( ! apply_filters( 'statify__skip_aggregation', false ) ) { + self::aggregate_data(); + } // Optimize DB. - $wpdb->query( - "OPTIMIZE TABLE `$wpdb->statify`" - ); + $wpdb->query( "OPTIMIZE TABLE `$wpdb->statify`" ); } /** diff --git a/tests/test-cron.php b/tests/test-cron.php index 2e125a2..57f5037 100644 --- a/tests/test-cron.php +++ b/tests/test-cron.php @@ -29,6 +29,8 @@ public function set_up() { * @preserveGlobalState disabled */ public function test_cronjob() { + global $wpdb; + // Initialize normal cycle, configure storage period of 3 days. $this->init_statify_widget( 3 ); $this->assertNotFalse( @@ -61,7 +63,8 @@ public function test_cronjob() { $this->assertEquals( 2, $v['count'], 'Unexpected visit count' ); } - // Run the cron job. + // Run the cron job without aggregation. + add_filter( 'statify__skip_aggregation', '__return_true' ); Statify_Cron::cleanup_data(); // Verify that 2 days have been deleted. @@ -72,6 +75,20 @@ public function test_cronjob() { $this->assertContains( $v['date'], $remaining_dates, 'Unexpected remaining date in stats' ); $this->assertEquals( 2, $v['count'], 'Unexpected visit count' ); } + $this->assertEquals( + 6, + $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->statify`" ), + 'Unexpected number of entries after cleanup without aggregation' + ); + + // Run the cron job with aggregation (default). + remove_filter( 'statify__skip_aggregation', '__return_true' ); + Statify_Cron::cleanup_data(); + $this->assertEquals( + 3, + $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->statify`" ), + 'Unexpected number of entries after cleanup with aggregation' + ); } /**