OptionSanitizer.php
68 lines
| 1 | <?php |
| 2 | /** |
| 3 | * FormatValidator class. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Internal\Settings; |
| 7 | |
| 8 | use Automattic\WooCommerce\Internal\Traits\AccessiblePrivateMethods; |
| 9 | |
| 10 | defined( 'ABSPATH' ) || exit; |
| 11 | |
| 12 | /** |
| 13 | * This class handles sanitization of core options that need to conform to certain format. |
| 14 | * |
| 15 | * @since 6.6.0 |
| 16 | */ |
| 17 | class OptionSanitizer { |
| 18 | |
| 19 | use AccessiblePrivateMethods; |
| 20 | |
| 21 | /** |
| 22 | * OptionSanitizer constructor. |
| 23 | */ |
| 24 | public function __construct() { |
| 25 | // Sanitize color options. |
| 26 | $color_options = array( |
| 27 | 'woocommerce_email_base_color', |
| 28 | 'woocommerce_email_background_color', |
| 29 | 'woocommerce_email_body_background_color', |
| 30 | 'woocommerce_email_text_color', |
| 31 | ); |
| 32 | |
| 33 | foreach ( $color_options as $option_name ) { |
| 34 | self::add_filter( |
| 35 | "woocommerce_admin_settings_sanitize_option_{$option_name}", |
| 36 | array( $this, 'sanitize_color_option' ), |
| 37 | 10, |
| 38 | 2 |
| 39 | ); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Sanitizes values for options of type 'color' before persisting to the database. |
| 45 | * Falls back to previous/default value for the option if given an invalid value. |
| 46 | * |
| 47 | * @since 6.6.0 |
| 48 | * @param string $value Option value. |
| 49 | * @param array $option Option data. |
| 50 | * @return string Color in hex format. |
| 51 | */ |
| 52 | private function sanitize_color_option( $value, $option ) { |
| 53 | $value = sanitize_hex_color( $value ); |
| 54 | |
| 55 | // If invalid, try the current value. |
| 56 | if ( ! $value && ! empty( $option['id'] ) ) { |
| 57 | $value = sanitize_hex_color( get_option( $option['id'] ) ); |
| 58 | } |
| 59 | |
| 60 | // If still invalid, try the default. |
| 61 | if ( ! $value && ! empty( $option['default'] ) ) { |
| 62 | $value = sanitize_hex_color( $option['default'] ); |
| 63 | } |
| 64 | |
| 65 | return (string) $value; |
| 66 | } |
| 67 | } |
| 68 |