Skip to content

Commit

Permalink
phpstan: refactor code to be more clear
Browse files Browse the repository at this point in the history
* 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)
  • Loading branch information
datengraben committed Jan 14, 2025
1 parent 8721fdf commit 0557c6c
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions src/Service/BookingRuleApplied.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
}

Expand Down

0 comments on commit 0557c6c

Please sign in to comment.