OptionSanitizer.php
68 lines
| 1 | <?php |
| 2 | /** |
| 3 | * FormatValidator class. |
| 4 | */ |
| 5 | |
| 6 | namespace Automattic\WooCommerce\Internal\Settings; |
| 7 | |
| 8 | defined( 'ABSPATH' ) || exit; |
| 9 | |
| 10 | /** |
| 11 | * This class handles sanitization of core options that need to conform to certain format. |
| 12 | * |
| 13 | * @since 6.6.0 |
| 14 | */ |
| 15 | class OptionSanitizer { |
| 16 | |
| 17 | /** |
| 18 | * OptionSanitizer constructor. |
| 19 | */ |
| 20 | public function __construct() { |
| 21 | // Sanitize color options. |
| 22 | $color_options = array( |
| 23 | 'woocommerce_email_base_color', |
| 24 | 'woocommerce_email_background_color', |
| 25 | 'woocommerce_email_body_background_color', |
| 26 | 'woocommerce_email_text_color', |
| 27 | ); |
| 28 | |
| 29 | foreach ( $color_options as $option_name ) { |
| 30 | add_filter( |
| 31 | "woocommerce_admin_settings_sanitize_option_{$option_name}", |
| 32 | array( $this, 'sanitize_color_option' ), |
| 33 | 10, |
| 34 | 2 |
| 35 | ); |
| 36 | } |
| 37 | // Cast "Out of stock threshold" field to absolute integer to prevent storing empty value. |
| 38 | add_filter( 'woocommerce_admin_settings_sanitize_option_woocommerce_notify_no_stock_amount', 'absint' ); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Sanitizes values for options of type 'color' before persisting to the database. |
| 43 | * Falls back to previous/default value for the option if given an invalid value. |
| 44 | * |
| 45 | * @since 6.6.0 |
| 46 | * @param string $value Option value. |
| 47 | * @param array $option Option data. |
| 48 | * @return string Color in hex format. |
| 49 | * |
| 50 | * @internal For exclusive usage of WooCommerce core, backwards compatibility not guaranteed. |
| 51 | */ |
| 52 | public 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 |