Completed
Push — add/cli-delete-connection-owne... ( 2ba2c2...25bd08 )
by Jeremy
174:17 queued 163:28
created

Initial_State::can_use_connection_iframe()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
1
<?php
2
/**
3
 * The React initial state.
4
 *
5
 * @package automattic/jetpack-connection-ui
6
 */
7
8
namespace Automattic\Jetpack\ConnectionUI;
9
10
use Automattic\Jetpack\Connection\Manager;
11
use Automattic\Jetpack\Connection\REST_Connector;
12
use Automattic\Jetpack\Constants;
13
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
14
15
/**
16
 * The React initial state.
17
 */
18
class Initial_State {
19
20
	/**
21
	 * The connection manager object.
22
	 *
23
	 * @var Manager
24
	 */
25
	private $manager;
26
27
	/**
28
	 * The constructor.
29
	 */
30
	public function __construct() {
31
		$this->manager = new Manager();
32
	}
33
34
	/**
35
	 * Get the initial state data.
36
	 *
37
	 * @return array
38
	 */
39
	private function get_data() {
40
		return array(
41
			'connectionStatus' => REST_Connector::connection_status( false ),
42
			'API'              => array(
43
				'WP_API_root'       => esc_url_raw( rest_url() ),
44
				'WP_API_nonce'      => wp_create_nonce( 'wp_rest' ),
45
				'registrationNonce' => wp_create_nonce( 'jetpack-registration-nonce' ),
46
			),
47
			'connectionData'   => array(
48
				'doNotUseConnectionIframe' => ! $this->can_use_connection_iframe(),
49
				'authorizationUrl'         => ( $this->manager->is_connected() && ! $this->manager->is_user_connected() )
50
					? $this->manager->get_authorization_url( null, admin_url( 'tools.php?page=wpcom-connection-manager' ) )
51
					: null,
52
			),
53
		);
54
	}
55
56
	/**
57
	 * Whether we can the connection iframe.
58
	 *
59
	 * @return bool
60
	 */
61
	private function can_use_connection_iframe() {
62
		global $is_safari;
63
64
		/**
65
		 * Filters whether the connection manager should use the iframe authorization
66
		 * flow instead of the regular redirect-based flow.
67
		 *
68
		 * @since 8.3.0
69
		 *
70
		 * @param Boolean $is_iframe_flow_used should the iframe flow be used, defaults to false.
71
		 */
72
		$iframe_flow = apply_filters( 'jetpack_use_iframe_authorization_flow', false );
73
74
		if ( ! $iframe_flow ) {
75
			return false;
76
		}
77
78
		return ! $is_safari && ! User_Agent_Info::is_opera_desktop() && ! Constants::is_true( 'JETPACK_SHOULD_NOT_USE_CONNECTION_IFRAME' );
79
	}
80
81
	/**
82
	 * Render the initial state into a JavaScript variable.
83
	 *
84
	 * @return string
85
	 */
86
	public function render() {
87
		add_action( 'jetpack_use_iframe_authorization_flow', '__return_true' );
88
89
		return 'var CUI_INITIAL_STATE=JSON.parse(decodeURIComponent("' . rawurlencode( wp_json_encode( $this->get_data() ) ) . '"));';
90
	}
91
92
}
93