Automattic\WooCommerce\Internal\PushNotifications\Dispatchers

WpcomNotificationDispatcher::dispatchpublicWC 10.7.0

Dispatches a notification with push tokens to WPCOM.

Method of the class: WpcomNotificationDispatcher{}

No Hooks.

Returns

Array{success:. bool, retry_after: int|null}

Usage

$WpcomNotificationDispatcher = new WpcomNotificationDispatcher();
$WpcomNotificationDispatcher->dispatch( $notification, $tokens ): array;
$notification(Notification) (required)
The notification to send.
$tokens(PushToken[]) (required)
The push tokens to send to.

Changelog

Since 10.7.0 Introduced.

WpcomNotificationDispatcher::dispatch() code WC 10.7.0

public function dispatch( Notification $notification, array $tokens ): array {
	$site_id = class_exists( Jetpack_Options::class ) ? Jetpack_Options::get_option( 'id' ) : null;

	if ( empty( $site_id ) ) {
		wc_get_logger()->error(
			'Cannot send push notifications: Jetpack site ID unavailable.',
			array( 'source' => PushNotifications::FEATURE_NAME )
		);

		return array(
			'success'     => false,
			'retry_after' => null,
		);
	}

	$payload = $notification->to_payload();

	if ( null === $payload ) {
		wc_get_logger()->error(
			sprintf(
				'Cannot send push notification: resource no longer exists (type=%s, resource_id=%d).',
				$notification->get_type(),
				$notification->get_resource_id()
			),
			array( 'source' => PushNotifications::FEATURE_NAME )
		);

		return array(
			'success'     => false,
			'retry_after' => null,
		);
	}

	$response = $this->make_request( $site_id, $payload, $tokens );

	if ( is_wp_error( $response ) ) {
		wc_get_logger()->error(
			sprintf(
				'Push notification request failed: %s',
				$response->get_error_message()
			),
			array( 'source' => PushNotifications::FEATURE_NAME )
		);

		return array(
			'success'     => false,
			'retry_after' => null,
		);
	}

	$status_code = (int) wp_remote_retrieve_response_code( $response );

	if ( WP_Http::OK === $status_code ) {
		return array(
			'success'     => true,
			'retry_after' => null,
		);
	}

	$retry_after = wp_remote_retrieve_header( $response, 'retry-after' );

	wc_get_logger()->error(
		sprintf(
			'Push notification request returned HTTP %d.',
			$status_code
		),
		array( 'source' => PushNotifications::FEATURE_NAME )
	);

	return array(
		'success'     => false,
		'retry_after' => '' !== $retry_after ? (int) $retry_after : null,
	);
}