*/ private $values; /** * Constructor. * * @param Registry $registry Registry. */ public function __construct( Registry $registry ) { $this->registry = $registry; $stored = get_option( CCTWEAKS_OPTION, array() ); $this->values = array_merge( Registry::defaults(), is_array( $stored ) ? $stored : array() ); } /** * Whether a tweak is switched on. * * @param string $id Tweak id. * @return bool */ public function is_enabled( $id ) { return ! empty( $this->values[ $id ] ); } /** * Returns a value (tweak toggle or field). * * @param string $key Key. * @param mixed $fallback Fallback when unset. * @return mixed */ public function get( $key, $fallback = null ) { return array_key_exists( $key, $this->values ) ? $this->values[ $key ] : $fallback; } /** * All values. * * @return array */ public function all() { return $this->values; } /** * Number of enabled tweaks. * * @return int */ public function enabled_count() { $n = 0; foreach ( array_keys( $this->registry->map() ) as $id ) { if ( $this->is_enabled( $id ) ) { ++$n; } } return $n; } /** * Sanitise callback for register_setting(). Builds a full, typed array from the registry, * so unknown keys are dropped and missing checkboxes become false. * * @param mixed $input Raw posted value. * @return array */ public function sanitize( $input ) { $input = is_array( $input ) ? $input : array(); $clean = array(); foreach ( $this->registry->map() as $id => $def ) { $clean[ $id ] = ! empty( $input[ $id ] ); if ( empty( $def['fields'] ) ) { continue; } foreach ( $def['fields'] as $fid => $field ) { $raw = isset( $input[ $fid ] ) ? $input[ $fid ] : null; switch ( $field['type'] ) { case 'number': $n = is_numeric( $raw ) ? (int) $raw : (int) $field['default']; if ( isset( $field['min'] ) ) { $n = max( (int) $field['min'], $n ); } if ( isset( $field['max'] ) ) { $n = min( (int) $field['max'], $n ); } $clean[ $fid ] = $n; break; case 'select': $raw = is_string( $raw ) ? sanitize_key( $raw ) : ''; $clean[ $fid ] = in_array( $raw, $field['options'], true ) ? $raw : $field['default']; break; case 'textarea': $clean[ $fid ] = is_string( $raw ) ? sanitize_textarea_field( wp_unslash( $raw ) ) : $field['default']; break; case 'post_types': $allowed = get_post_types( array( 'show_ui' => true ), 'names' ); $raw = is_array( $raw ) ? array_map( 'sanitize_key', $raw ) : array(); $clean[ $fid ] = array_values( array_intersect( $raw, $allowed ) ); break; default: $clean[ $fid ] = is_scalar( $raw ) ? sanitize_text_field( (string) $raw ) : $field['default']; } } } return $clean; } }