radio_default_station_id(), // Groove Salad 'volume' => 0.6, // 60% — comfortable default 'theme' => 'auto', // auto = match site admin colour scheme 'last_played_at' => 0, ); } /** * Fetch the current user's state, falling back to defaults and * persisting them on first read so a baseline exists for AJAX patches. * * @param int $user_id Optional. Defaults to current user. * @return array */ function radio_get_state( $user_id = 0 ) { $user_id = $user_id ? (int) $user_id : get_current_user_id(); if ( ! $user_id ) { return radio_default_state(); } $state = get_user_meta( $user_id, RADIO_META_KEY, true ); if ( ! is_array( $state ) || empty( $state ) ) { $state = radio_default_state(); update_user_meta( $user_id, RADIO_META_KEY, $state ); } // Merge any newly-introduced default keys forward without trampling // existing user values. $state = array_merge( radio_default_state(), $state ); // Validate station — if it's been removed from stations.php, fall // back to the default rather than rendering a dead choice. if ( ! radio_find_station( $state['station_id'] ) ) { $state['station_id'] = radio_default_station_id(); } // Clamp volume to [0, 1]. $state['volume'] = max( 0.0, min( 1.0, (float) $state['volume'] ) ); return $state; } /** * Apply a partial update to the current user's state. Only keys in * `radio_default_state()` are persisted; everything else is dropped. * * @param array $patch * @param int $user_id Optional. Defaults to current user. * @return array The new state. */ function radio_update_state( array $patch, $user_id = 0 ) { $user_id = $user_id ? (int) $user_id : get_current_user_id(); if ( ! $user_id ) { return radio_default_state(); } $state = radio_get_state( $user_id ); $allowed = array_keys( radio_default_state() ); $filtered = array_intersect_key( $patch, array_flip( $allowed ) ); if ( isset( $filtered['station_id'] ) ) { $filtered['station_id'] = sanitize_key( $filtered['station_id'] ); if ( ! radio_find_station( $filtered['station_id'] ) ) { unset( $filtered['station_id'] ); } } if ( isset( $filtered['volume'] ) ) { $filtered['volume'] = max( 0.0, min( 1.0, (float) $filtered['volume'] ) ); } if ( isset( $filtered['theme'] ) ) { $filtered['theme'] = in_array( $filtered['theme'], array( 'auto', 'light', 'dark' ), true ) ? $filtered['theme'] : 'auto'; } $new_state = array_merge( $state, $filtered ); $new_state['last_played_at'] = time(); update_user_meta( $user_id, RADIO_META_KEY, $new_state ); return $new_state; }