Completed
Pull Request — master (#1267)
by
unknown
01:45
created

WC_Stripe_Connect   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 201
Duplicated Lines 2.99 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 6
loc 201
rs 10
c 0
b 0
f 0
wmc 26
lcom 1
cbo 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A get_oauth_url() 0 20 4
A deauthorize_account() 0 12 2
A connect_oauth() 0 16 3
A maybe_connect_oauth() 0 13 3
A save_stripe_keys() 0 25 4
A clear_stripe_keys() 0 20 2
A wc_ajax_oauth_init() 3 14 4
A wc_ajax_clear_stripe_keys() 3 10 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	exit;
5
}
6
7
if ( ! class_exists( 'WC_Stripe_Connect' ) ) {
8
	/**
9
	 * Stripe Connect class.
10
	 */
11
	class WC_Stripe_Connect {
12
13
		const SETTINGS_OPTION = 'woocommerce_stripe_settings';
14
15
		/**
16
		 * Stripe connect api.
17
		 *
18
		 * @var object $api
19
		 */
20
		private $api;
21
22
		/**
23
		 * Constructor.
24
		 *
25
		 * @param WC_Stripe_Connect_API $api stripe connect api.
26
		 */
27
		public function __construct( WC_Stripe_Connect_API $api ) {
28
29
			$this->api = $api;
30
31
			add_action( 'wc_ajax_wc_stripe_oauth_init', array( $this, 'wc_ajax_oauth_init' ) );
32
			add_action( 'wc_ajax_wc_stripe_clear_keys', array( $this, 'wc_ajax_clear_stripe_keys' ) );
33
		}
34
35
		/**
36
		 * Gets the OAuth URL for Stripe onboarding flow
37
		 *
38
		 * @param  string $return_url url to return to after oauth flow.
39
		 *
40
		 * @return string|WP_Error
41
		 */
42
		public function get_oauth_url( $return_url = '' ) {
43
44
			if ( empty( $return_url ) ) {
45
				$return_url = admin_url( 'admin.php?page=wc-settings&tab=checkout&section=stripe' );
46
			}
47
48
			if ( substr( $return_url, 0, 8 ) !== 'https://' ) {
49
				return new WP_Error( 'invalid_url_protocol', __( 'Your site must be served over HTTPS in order to connect your Stripe account automatically.', 'woocommerce-gateway-stripe' ) );
50
			}
51
52
			$result = $this->api->get_stripe_oauth_init( $return_url );
53
54
			if ( is_wp_error( $result ) ) {
55
				return $result;
56
			}
57
58
			update_option( 'stripe_state', $result->state );
59
60
			return $result->oauthUrl; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
61
		}
62
63
		/**
64
		 * Deauthorize existing Stripe account
65
		 *
66
		 * @return array|WP_Error
67
		 */
68
		public function deauthorize_account() {
69
70
			$response = $this->api->deauthorize_stripe_account();
71
72
			if ( is_wp_error( $response ) ) {
73
				return $response;
74
			}
75
76
			$this->clear_stripe_keys();
77
78
			return $response;
79
		}
80
81
		/**
82
		 * Initiate OAuth connection request to Connect Server
83
		 *
84
		 * @param  bool $state Stripe onboarding state.
85
		 * @param  int  $code  OAuth code.
86
		 *
87
		 * @return string|WP_Error
88
		 */
89
		public function connect_oauth( $state, $code ) {
90
91
			if ( get_option( 'stripe_state', false ) !== $state ) {
92
				return new WP_Error( 'Invalid stripe state' );
93
			}
94
95
			$response = $this->api->get_stripe_oauth_keys( $code );
96
97
			if ( is_wp_error( $response ) ) {
98
				return $response;
99
			}
100
101
			delete_option( 'stripe_state' );
102
103
			return $this->save_stripe_keys( $response );
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->save_stripe_keys($response); of type WP_Error|array adds the type array to the return on line 103 which is incompatible with the return type documented by WC_Stripe_Connect::connect_oauth of type string|WP_Error.
Loading history...
104
		}
105
106
		/**
107
		 * Handle redirect back from oauth-init
108
		 */
109
		public function maybe_connect_oauth() {
110
111
			if ( ! get_option( 'stripe_state', false ) ) {
112
				return;
113
			}
114
115
			if ( isset( $_GET['wcs_stripe_code'], $_GET['wcs_stripe_state'] ) ) {
116
				$response = $this->connect_oauth( $_GET['wcs_stripe_state'], $_GET['wcs_stripe_code'] );
0 ignored issues
show
Unused Code introduced by
$response is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
117
118
				wp_safe_redirect( remove_query_arg( array( 'wcs_stripe_state', 'wcs_stripe_code' ) ) );
119
				exit;
120
			}
121
		}
122
123
		/**
124
		 * Saves stripe keys after OAuth response
125
		 *
126
		 * @param  array $result OAuth response result.
127
		 *
128
		 * @return array|WP_Error
129
		 */
130
		private function save_stripe_keys( $result ) {
131
132
			if ( ! isset( $result->publishableKey, $result->secretKey ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
133
				return new WP_Error( 'Invalid credentials received from WooCommerce Connect server' );
134
			}
135
136
			$is_test         = false !== strpos( $result->publishableKey, '_test_' ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
137
			$prefix          = $is_test ? 'test_' : '';
138
			$default_options = array();
139
140
			$options                                = array_merge( $default_options, get_option( self::SETTINGS_OPTION, array() ) );
141
			$options['enabled']                     = 'yes';
142
			$options['testmode']                    = $is_test ? 'yes' : 'no';
143
			$options[ $prefix . 'publishable_key' ] = $result->publishableKey; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
144
			$options[ $prefix . 'secret_key' ]      = $result->secretKey; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
145
146
			// While we are at it, let's also clear the account_id and
147
			// test_account_id if present.
148
			unset( $options['account_id'] );
149
			unset( $options['test_account_id'] );
150
151
			update_option( self::SETTINGS_OPTION, $options );
152
153
			return $result;
154
		}
155
156
		/**
157
		 * Clears keys for test or production (whichever is presently enabled).
158
		 */
159
		private function clear_stripe_keys() {
160
161
			$options = get_option( self::SETTINGS_OPTION, array() );
162
163
			if ( 'yes' === $options['testmode'] ) {
164
				$options['test_publishable_key'] = '';
165
				$options['test_secret_key']      = '';
166
			} else {
167
				$options['publishable_key'] = '';
168
				$options['secret_key']      = '';
169
			}
170
171
			// While we are at it, let's also clear the account_id and
172
			// test_account_id if present.
173
			unset( $options['account_id'] );
174
			unset( $options['test_account_id'] );
175
176
			update_option( self::SETTINGS_OPTION, $options );
177
178
		}
179
180
		/**
181
		 * Gets Stripe Connect Oauth url and redirects to Stripe.
182
		 */
183
		public function wc_ajax_oauth_init() {
184
185 View Code Duplication
			if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], '_wc_stripe_admin_nonce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
				wp_die( __( 'You are not authorized to automatically copy Stripe keys.', 'woocommerce-gateway-stripe' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
187
			}
188
189
			$oauth_url = $this->get_oauth_url();
190
191
			if ( is_wp_error( $oauth_url ) ) {
192
				wp_send_json_error( $oauth_url->get_error_message() );
193
			}
194
195
			wp_send_json_success( $oauth_url );
196
		}
197
198
		/**
199
		 * Clear stripe keys.
200
		 */
201
		public function wc_ajax_clear_stripe_keys() {
202
203 View Code Duplication
			if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], '_wc_stripe_admin_nonce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
204
				wp_die( __( 'You are not authorized to reset Stripe keys.', 'woocommerce-gateway-stripe' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
205
			}
206
207
			$this->clear_stripe_keys();
208
209
			wp_send_json_success( admin_url( 'admin.php?page=wc-settings&tab=checkout&section=stripe' ) );
210
		}
211
	}
212
}
213