Fix Rules screen crash: Store::rules() discarded decoded config (by-ref foreach over a cast copy)
Also make an unreadable rule non-fatal on the Rules screen, and add a regression test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3bbd77b661
commit
27646c1001
3 files changed
+67
-3
No files matched your search
@@ -197,7 +197,13 @@ final class GoalsPage {
|
||||
foreach ( $rules as $r ) {
|
||||
$rid = (int) $r['id'];
|
||||
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '"><td>' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
|
||||
echo '<td>' . esc_html( RuleConfig::summary( (string) $r['type'], $r['config'], $cur ) ) . '</td><td class="sg-actions">';
|
||||
try {
|
||||
$summary = RuleConfig::summary( (string) $r['type'], $r['config'], $cur );
|
||||
} catch ( \Throwable $e ) {
|
||||
// One unreadable rule must not take down the whole screen; say what is wrong so it can be fixed or deleted.
|
||||
$summary = 'Could not read this rule (' . $e->getMessage() . '). You can delete it and add it again.';
|
||||
}
|
||||
echo '<td>' . esc_html( $summary ) . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId, 'rule' => $rid ) ) ) . '#sg-rule-form">Edit</a> ';
|
||||
Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' );
|
||||
echo '<button class="button">' . ( $r['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
|
||||
|
||||
@@ -26,11 +26,14 @@ final class Store {
|
||||
public static function rules( int $goalId ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d ORDER BY sort ASC, id ASC', $goalId ), ARRAY_A );
|
||||
foreach ( (array) $rows as &$r ) {
|
||||
$rows = (array) $rows;
|
||||
// Iterate $rows itself by reference: `foreach ( (array) $rows as &$r )` would modify a temporary copy and discard the decoding.
|
||||
foreach ( $rows as &$r ) {
|
||||
$cfg = json_decode( (string) $r['config'], true );
|
||||
$r['config'] = is_array( $cfg ) ? $cfg : array();
|
||||
}
|
||||
return (array) $rows;
|
||||
unset( $r );
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public static function rule( int $ruleId, int $goalId ): ?array {
|
||||
|
||||
Reference in new issue
Block a user