Automattic\WooCommerce\Internal\PushNotifications\Validators
PushTokenValidator::validate_token
Validates token value.
Method of the class: PushTokenValidator{}
No Hooks.
Returns
true|false|WP_Error.
Usage
$result = PushTokenValidator::validate_token( $value, ?array $context );
- $value(mixed) (required)
- The value to validate.
- ?array $context
- .
Default:array()
Changelog
| Since 10.6.0 | Introduced. |
PushTokenValidator::validate_token() PushTokenValidator::validate token code WC 10.8.1
private static function validate_token( $value, ?array $context = array() ) {
if ( is_null( $value ) ) {
return new WP_Error( self::ERROR_CODE, 'Token is required.' );
}
if ( ! is_string( $value ) ) {
return new WP_Error( self::ERROR_CODE, 'Token must be a string.' );
}
$value = trim( $value );
if ( '' === $value ) {
return new WP_Error( self::ERROR_CODE, 'Token cannot be empty.' );
}
if ( strlen( $value ) > self::TOKEN_MAXIMUM_LENGTH ) {
return new WP_Error(
self::ERROR_CODE,
sprintf( 'Token exceeds maximum length of %s.', self::TOKEN_MAXIMUM_LENGTH )
);
}
if ( ! isset( $context['platform'] ) ) {
/**
* We don't know how to validate the format as we don't know the
* platform, so let the platform validation handle the failure.
*/
return true;
}
if (
PushToken::PLATFORM_APPLE === $context['platform']
&& ! preg_match( self::TOKEN_FORMAT_APPLE, $value )
) {
return new WP_Error( self::ERROR_CODE, 'Token is an invalid format.' );
}
if (
PushToken::PLATFORM_ANDROID === $context['platform']
&& ! preg_match( self::TOKEN_FORMAT_ANDROID, $value )
) {
return new WP_Error( self::ERROR_CODE, 'Token is an invalid format.' );
}
if ( PushToken::PLATFORM_BROWSER === $context['platform'] ) {
$token_object = json_decode( $value, true );
$endpoint = $token_object['endpoint'] ?? null;
if (
is_null( $token_object )
|| json_last_error()
|| ! isset( $token_object['keys']['auth'] )
|| ! isset( $token_object['keys']['p256dh'] )
|| ! $endpoint
|| ! wp_http_validate_url( (string) $endpoint )
|| ( wp_parse_url( (string) $endpoint, PHP_URL_SCHEME ) !== 'https' )
) {
return new WP_Error( self::ERROR_CODE, 'Token is an invalid format.' );
}
}
return true;
}