true, 'desktop' => true, 'mobile' => true, 'position' => 'bottom', 'trigger' => 'scroll', 'show_image' => true, 'show_price' => true, 'show_qty' => true, 'button_text' => '', 'style' => 'light', 'button_color' => '', 'delete_data' => false, ); } /** * Allowed values for the choice settings. * * @return array */ public static function choices() { return array( 'position' => array( 'bottom', 'top' ), 'trigger' => array( 'scroll', 'always' ), 'style' => array( 'light', 'dark' ), ); } /** * Current settings merged over the defaults. * * @return array */ public static function get() { if ( null === self::$cache ) { $saved = get_option( self::OPTION, array() ); self::$cache = self::sanitize( is_array( $saved ) ? $saved : array() ); } return self::$cache; } /** * Cleans raw input (from the form or the database) into a full settings array. * * @param array $input Raw values. * @return array */ public static function sanitize( array $input ) { $defaults = self::defaults(); $clean = array(); foreach ( $defaults as $key => $default ) { $value = array_key_exists( $key, $input ) ? $input[ $key ] : $default; if ( is_bool( $default ) ) { $clean[ $key ] = (bool) $value && '0' !== $value; } elseif ( isset( self::choices()[ $key ] ) ) { $value = sanitize_key( (string) $value ); $clean[ $key ] = in_array( $value, self::choices()[ $key ], true ) ? $value : $default; } elseif ( 'button_color' === $key ) { $color = sanitize_hex_color( (string) $value ); $clean[ $key ] = $color ? $color : ''; } else { $clean[ $key ] = sanitize_text_field( (string) $value ); } } return $clean; } /** * Saves settings from the form. * * @param array $input Raw form values. */ public static function save( array $input ) { $clean = self::sanitize( $input ); update_option( self::OPTION, $clean ); self::$cache = $clean; } /** * Black or white text, whichever reads better on a background color. * * @param string $hex Background color (#rrggbb or #rgb). * @return string */ public static function text_color_for( $hex ) { $hex = ltrim( (string) $hex, '#' ); if ( 3 === strlen( $hex ) ) { $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; } if ( 6 !== strlen( $hex ) ) { return '#ffffff'; } $channel = static function ( $part ) { $c = hexdec( $part ) / 255; return $c <= 0.03928 ? $c / 12.92 : pow( ( $c + 0.055 ) / 1.055, 2.4 ); }; $lum = 0.2126 * $channel( substr( $hex, 0, 2 ) ) + 0.7152 * $channel( substr( $hex, 2, 2 ) ) + 0.0722 * $channel( substr( $hex, 4, 2 ) ); // Contrast with white is (1.05) / (lum + 0.05); with black (lum + 0.05) / 0.05. Pick the higher one. return ( 1.05 / ( $lum + 0.05 ) ) >= ( ( $lum + 0.05 ) / 0.05 ) ? '#ffffff' : '#111111'; } }