'replace', 'hide_cut' => false, 'hide_copy_add' => false, 'hide_transfer' => false, 'section_content' => false, ); /** * Preferences of a user, defaults filled in. * * @param int $user_id User ID. * @return array */ public static function get( int $user_id ): array { $stored = get_user_meta( $user_id, self::META_KEY, true ); return self::sanitize( is_array( $stored ) ? $stored : array() ); } /** * Whether a user ever saved preferences. * * @param int $user_id User ID. */ public static function exists( int $user_id ): bool { return metadata_exists( 'user', $user_id, self::META_KEY ); } /** * Merges changes into a user's preferences and saves them. * * @param int $user_id User ID. * @param array $changes Preferences to change; unknown keys are ignored. * @return array Saved preferences. */ public static function update( int $user_id, array $changes ): array { $prefs = self::sanitize( array_merge( self::get( $user_id ), $changes ) ); update_user_meta( $user_id, self::META_KEY, $prefs ); return $prefs; } /** * Keeps known keys only, with valid values; anything else falls back to the default. * * @param array $input Raw preferences. * @return array */ public static function sanitize( array $input ): array { $prefs = self::DEFAULTS; if ( isset( $input['copy_mode'] ) && in_array( $input['copy_mode'], self::COPY_MODES, true ) ) { $prefs['copy_mode'] = $input['copy_mode']; } foreach ( array( 'hide_cut', 'hide_copy_add', 'hide_transfer', 'section_content' ) as $key ) { if ( isset( $input[ $key ] ) ) { $prefs[ $key ] = (bool) filter_var( $input[ $key ], FILTER_VALIDATE_BOOLEAN ); } } return $prefs; } /** * JSON schema of the preferences, for the REST route. * * @return array */ public static function schema(): array { return array( 'copy_mode' => array( 'type' => 'string', 'enum' => self::COPY_MODES, ), 'hide_cut' => array( 'type' => 'boolean' ), 'hide_copy_add' => array( 'type' => 'boolean' ), 'hide_transfer' => array( 'type' => 'boolean' ), 'section_content' => array( 'type' => 'boolean' ), ); } }