From 0557c6c750208bc16e67cb6996acca4c0468dddd Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 14 Jan 2025 15:29:00 +0100 Subject: [PATCH] phpstan: refactor code to be more clear * remove unneccessary null/isset checks * catch rule object creation exceptions * checks for 'false' return of wp_json_encode * logs to error when WP_DEBUG * return '' // graceful return in admin settings page (as stated in docstring) --- src/Service/BookingRuleApplied.php | 33 ++++++++++++++++-------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/Service/BookingRuleApplied.php b/src/Service/BookingRuleApplied.php index ed88e9e27..65f9b1ccd 100644 --- a/src/Service/BookingRuleApplied.php +++ b/src/Service/BookingRuleApplied.php @@ -8,6 +8,7 @@ use CommonsBooking\Repository\UserRepository; use CommonsBooking\Settings\Settings; use CommonsBooking\Wordpress\Options\OptionsTab; +use Exception; /** * Represents a valid configuration of a {@see BookingRule}, which can be applied to bookings. @@ -187,24 +188,26 @@ public static function bookingConformsToRules( Booking $booking):void { } /** - * Gets a string of all rule properties, so they can be displayed using CMB2 + * Retrieves a JSON string of all rule properties to display using CMB2. * - * Will ignore errors, so that the settings page can still display the selected values even if they are invalid - * @return string + * If initialization or encoding fails, returns an empty string to ensure the page functions. + * + * @return string JSON-encoded rule properties, or an empty string on failure. */ public static function getRulesJSON(): string { - $ruleObjects = static::init( true ); - - if ( isset( $ruleObjects ) ) { - return wp_json_encode( - array_map( - function( $rule){ - return get_object_vars($rule); - }, $ruleObjects ) - ); - } - else { - return ""; + try { + $ruleObjects = static::init(true); + + // Ensure we return valid JSON or an empty string if encoding fails + return wp_json_encode(array_map(function($rule) { + return get_object_vars($rule); + }, $ruleObjects)) ?: ''; + } catch (Exception $e) { + if (WP_DEBUG) { + error_log( $e->getMessage() ); + } + + return ''; // Return an empty string if initialization or encoding fails } }