Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
61.54% covered (warning)
61.54%
8 / 13
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Wpcom_Request_Client
61.54% covered (warning)
61.54%
8 / 13
0.00% covered (danger)
0.00%
0 / 2
13.61
0.00% covered (danger)
0.00%
0 / 1
 is_user_connected
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 request
66.67% covered (warning)
66.67%
8 / 12
0.00% covered (danger)
0.00%
0 / 1
10.37
1<?php
2/**
3 * Jetpack WP.com request client.
4 *
5 * @package automattic/jetpack-help-center
6 */
7
8namespace Automattic\Jetpack\Help_Center;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Connection\Manager;
12
13/**
14 * Sends WP.com requests through Jetpack Connection or anonymously.
15 */
16final class Jetpack_Wpcom_Request_Client implements Wpcom_Request_Client {
17    /**
18     * Whether the current user has a Jetpack user connection.
19     *
20     * @return bool
21     */
22    public function is_user_connected() {
23        return ( new Manager( 'jetpack' ) )->is_user_connected();
24    }
25
26    /**
27     * Send a request to WordPress.com.
28     *
29     * Logged-in requests use the current Jetpack-connected user. Logged-out
30     * requests are sent directly to the public WordPress.com API.
31     *
32     * @param string            $path          REST API path.
33     * @param string            $version       REST API version.
34     * @param array             $args          Arguments passed to WP_Http.
35     * @param array|string|null $body          Request body.
36     * @param string            $base_api_path REST API root.
37     *
38     * @return array|\WP_Error Response data, or WP_Error on failure.
39     */
40    public function request(
41        $path,
42        $version = '2',
43        $args = array(),
44        $body = null,
45        $base_api_path = 'wpcom'
46    ) {
47        if ( is_user_logged_in() ) {
48            return Client::wpcom_json_api_request_as_user( $path, $version, $args, $body, $base_api_path );
49        }
50
51        $request_args = Client::validate_args_for_wpcom_json_api_request( $path, $version, $args, $base_api_path );
52        $url          = $request_args['url'];
53        unset( $request_args['url'] );
54
55        if ( isset( $body ) && ! isset( $request_args['headers'] ) && in_array( $request_args['method'], array( 'POST', 'PUT', 'PATCH' ), true ) ) {
56            $request_args['headers'] = array( 'Content-Type' => 'application/json' );
57        }
58
59        if ( isset( $body ) && ! is_string( $body ) ) {
60            $body = wp_json_encode( $body, JSON_UNESCAPED_SLASHES );
61        }
62
63        if ( isset( $body ) ) {
64            $request_args['body'] = $body;
65        }
66
67        return wp_remote_request( $url, $request_args );
68    }
69}