| 1 |
<?php |
| 2 |
/** |
| 3 |
* Customer role meta protection. |
| 4 |
* |
| 5 |
* @package WCPOS\WooCommercePOS |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WCPOS\WooCommercePOS\Services; |
| 9 |
|
| 10 |
/** |
| 11 |
* Roles and levels change only through the WP_User role APIs. |
| 12 |
*/ |
| 13 |
final class Role_Meta_Guard { |
| 14 |
/** |
| 15 |
* Register after other customer meta listeners. |
| 16 |
*/ |
| 17 |
public static function register(): void { |
| 18 |
add_action( 'woocommerce_before_customer_object_save', array( self::class, 'strip_role_meta' ), PHP_INT_MAX ); |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* Strip role metadata that WooCommerce copies onto the customer as generic meta. |
| 23 |
* |
| 24 |
* @param mixed $customer Object being saved. |
| 25 |
*/ |
| 26 |
public static function strip_role_meta( $customer ): void { |
| 27 |
if ( ! $customer instanceof \WC_Customer ) { |
| 28 |
return; |
| 29 |
} |
| 30 |
|
| 31 |
foreach ( $customer->get_meta_data() as $meta ) { |
| 32 |
if ( self::is_role_meta_key( $meta->key ) ) { |
| 33 |
if ( $meta->id ) { |
| 34 |
$customer->delete_meta_data_by_mid( $meta->id ); |
| 35 |
} else { |
| 36 |
$customer->delete_meta_data( $meta->key ); |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Identify role and level metadata for any blog prefix. |
| 44 |
* |
| 45 |
* @param mixed $key Meta key. |
| 46 |
* @return bool Whether the key stores roles or a user level. |
| 47 |
*/ |
| 48 |
public static function is_role_meta_key( $key ): bool { |
| 49 |
if ( ! \is_string( $key ) ) { |
| 50 |
return false; |
| 51 |
} |
| 52 |
|
| 53 |
global $wpdb; |
| 54 |
|
| 55 |
return 1 === preg_match( '/^' . preg_quote( $wpdb->base_prefix, '/' ) . '(\d+_)?(capabilities|user_level)$/i', trim( $key ) ); |
| 56 |
} |
| 57 |
} |
| 58 |
|