Completed
Push — master ( 2a60ef...645aad )
by Zack
53:50 queued 48:17
created

GravityView_Field_Unsubscribe   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 265
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 48.35%

Importance

Changes 0
Metric Value
dl 0
loc 265
ccs 44
cts 91
cp 0.4835
rs 8.8798
c 0
b 0
f 0
wmc 44
lcom 1
cbo 3

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A add_hooks() 0 7 1
A field_options() 0 18 1
A maybe_not_visible() 0 6 3
C filter_gravityview_entry_default_field() 0 42 12
B modify_entry_value_unsubscribe() 0 39 10
C maybe_unsubscribe() 0 56 16

How to fix   Complexity   

Complex Class

Complex classes like GravityView_Field_Unsubscribe often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GravityView_Field_Unsubscribe, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @file class-gravityview-field-unsubscribe.php
4
 * @since 2.5
5
 * @package GravityView
6
 * @subpackage includes\fields
7
 */
8
9
class GravityView_Field_Unsubscribe extends GravityView_Field {
10
11
	var $name = 'unsubscribe';
12
13
	var $group = 'gravityview';
14
15
	var $is_searchable = false;
16
17
	var $contexts = array( 'single', 'multiple' );
18
19
	public function __construct() {
20
		$this->label = esc_html__( 'Unsubscribe', 'gravityview' );
21
		$this->description =  esc_attr__( 'Unsubscribe from a Payment-based entry.', 'gravityview' );
22
23
		$this->add_hooks();
24
25
		parent::__construct();
26
	}
27
28
	/**
29
	 * Hooks called from constructor.
30
	 *
31
	 * @return void
32
	 */
33
	public function add_hooks() {
34
		add_filter( 'gravityview_entry_default_fields', array( $this, 'filter_gravityview_entry_default_field' ), 10, 3 );
35
36
		add_filter( 'gravityview/field/is_visible', array( $this, 'maybe_not_visible' ), 10, 2 );
37
38
		add_filter( 'gravityview_field_entry_value_unsubscribe', array( $this, 'modify_entry_value_unsubscribe' ), 10, 4 );
39
	}
40
41
	/**
42
	 * Configure the field options.
43
	 *
44
	 * Called from the `gravityview_entry_default_fields` filter.
45
	 *
46
	 * Remove the logged in, new window and show as link options.
47
	 * Add the allow unsubscribe for all admins option.
48
	 *
49
	 * @param array $field_options The options.
50
	 * @param string $template_id The template ID.
51
	 * @param int|string|float $field_id The field ID.
52
	 * @param string $context The configuration context (edit, single, etc.)
53
	 * @param string $input_type The input type.
54
	 * @param int $form_id The form ID.
55
	 *
56
	 * @return array The field options.
57
	 */
58
	public function field_options( $field_options, $template_id, $field_id, $context, $input_type, $form_id ) {
59
60
		unset( $field_options['only_loggedin'] );
61
62
		unset( $field_options['new_window'] );
63
64
		unset( $field_options['show_as_link'] );
65
66
		$add_options['unsub_all'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$add_options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $add_options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
67
			'type'       => 'checkbox',
68
			'label'      => __( 'Allow admins to unsubscribe', 'gravityview' ),
69
			'desc'       => __( 'Allow users with `gravityforms_edit_entries` to cancel subscriptions', 'gravityview' ),
70
			'value'      => false,
71
			'merge_tags' => false,
72
		);
73
74
		return $field_options + $add_options;
75
	}
76
77
	/**
78
	 * Hide the field from the renderer. Perhaps.
79
	 *
80
	 * Called from `gravityview/field/is_visible`
81
	 *
82
	 * Hide the field for non-logged in users for sure.
83
	 *
84
	 * @param bool $visible Consider visible or not.
85
	 * @param \GV\Field $field The field.
86
	 *
87
	 * @return bool Visible or not.
88
	 */
89 45
	public function maybe_not_visible( $visible, $field ) {
90 45
		if ( $this->name !== $field->ID ) {
91 44
			return $visible;
92
		}
93 1
		return is_user_logged_in() ? $visible : false;
94
	}
95
96
	/**
97
	 * Add the unsubsribe to the configuration fields.
98
	 *
99
	 * Only if a subscription feed is active for the current form.
100
	 *
101
	 * Called from `gravityview_entry_default_fields`
102
	 *
103
	 * @param array $entry_default_fields An array of available for configuration.
104
	 * @param array $form The form.
105
	 * @param string $context The configuration context (edit, single, etc.)
106
	 *
107
	 * @return array The array of available default fields.
108
	 */
109
	public function filter_gravityview_entry_default_field( $entry_default_fields, $form, $context ) {
110
111
		$feeds = GFAPI::get_feeds( null, $form );
112
113
		if ( is_wp_error( $feeds ) ) {
114
			return $entry_default_fields;
115
		}
116
117
		static $subscription_addons;
118
119
		if ( is_null( $subscription_addons ) ) {
120
121
			$registered = GFAddon::get_registered_addons();
122
123
			foreach ( $registered as $addon ) {
124
				if ( method_exists( $addon, 'cancel_subscription' ) && is_callable( array( $addon, 'get_instance' ) ) ) {
125
					$addon = $addon::get_instance();
126
					$subscription_addons[ $addon->get_slug() ] = $addon;
127
				}
128
			}
129
		}
130
131
		if ( empty( $subscription_addons ) ) {
132
			return $entry_default_fields;
133
		}
134
135
		foreach ( $feeds as $feed ) {
136
			if ( isset( $subscription_addons[ $feed['addon_slug'] ] ) && 'subscription' === \GV\Utils::get( $feed, 'meta/transactionType' ) ) {
137
				if ( ! isset( $entry_default_fields["{$this->name}"] ) && 'edit' !== $context ) {
138
					$entry_default_fields["{$this->name}"] = array(
139
						'label' => $this->label,
140
						'desc'  => $this->description,
141
						'type'  => $this->name,
142
					);
143
144
					break; // Feed found, field added
145
				}
146
			}
147
		}
148
149
		return $entry_default_fields;
150
	}
151
152
	/**
153
	 * Modify the render content.
154
	 *
155
	 * Called from `gravityview_field_entry_value_unsubscribe`
156
	 *
157
	 * @param string $output The output.
158
	 * @param array $entry The entry.
159
	 * @param array $field_settings The field settings.
160
	 * @param \GV\Field $field The field.
161
	 *
162
	 * @return string The content.
163
	 */
164 2
	public function modify_entry_value_unsubscribe( $output, $entry, $field_settings, $field ) {
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
165 2
		if ( ! is_user_logged_in() ) {
166 1
			return $output;
167
		}
168
169 2
		$can_current_user_edit = is_numeric( $entry['created_by'] ) && ( wp_get_current_user()->ID === intval( $entry['created_by'] ) );
170
171 2
		if ( ! $can_current_user_edit ) {
172 1
			if ( empty( $field_settings['unsub_all'] ) || ! \GVCommon::has_cap( 'gravityforms_edit_entries', $entry['id'] ) ) {
173 1
				return $output;
174
			}
175
		}
176
177 2
		if ( ! $status = \GV\Utils::get( $entry, 'payment_status' ) ) {
178 1
			return $output;
179
		}
180
181
		// @todo Move to init, or AJAXify, but make sure that the entry is in the View before allowing
182
		// @todo Also make sure we check caps if moved from here
183
		// @todo Also make sure test_GravityView_Field_Unsubscribe_unsubscribe_permissions is rewritten
184 2
		if ( $entry = $this->maybe_unsubscribe( $entry ) ) {
185 2
			if ( $entry['payment_status'] !== $status ) {
186
				// @todo Probably __( 'Unsubscribed', 'gravityview' );
187 1
				return $entry['payment_status'];
188
			}
189
		}
190
191 2
		if ( 'active' !== mb_strtolower( $entry['payment_status'] ) ) {
192 1
			return $output;
193
		}
194
195 2
		global $wp;
196 2
		$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
197
198 2
		$link = add_query_arg( 'unsubscribe', wp_create_nonce( 'unsubscribe_' . $entry['id'] ), $current_url );
199 2
		$link = add_query_arg( 'uid', $entry['id'], $link );
200
201 2
		return sprintf( '<a href="%s">%s</a>', esc_url( $link ), esc_html__( 'Unsubscribe', 'gravityview' ) );
202
	}
203
204
	/**
205
	 * Try to unsubscribe from the entry.
206
	 *
207
	 * Called during a POST request. Checks nonce, feeds, entry ID.
208
	 * Does not check user permissions. This is left as an exercise for the caller.
209
	 *
210
	 * Entry View inclusion is checked ad-hoc during the rendering of the field.
211
	 * User permissions are also checked ad-hoc during the rendering process.
212
	 *
213
	 * @param array $entry The entry
214
	 *
215
	 * @return array $entry The entry
216
	 */
217 2
	private function maybe_unsubscribe( $entry ) {
218
219 2
		if ( ! wp_verify_nonce( \GV\Utils::_REQUEST( 'unsubscribe' ), 'unsubscribe_' . $entry['id'] ) ) {
220 2
			return $entry;
221
		}
222
223 1
		if ( ( ! $uid = \GV\Utils::_REQUEST( 'uid' ) ) || ! is_numeric( $uid ) || ( intval( $uid ) !== intval( $entry['id'] ) ) ) {
224
			return $entry;
225
		}
226
227 1
		if ( ! $feeds = gform_get_meta( $uid, 'processed_feeds' ) ) {
228
			return $entry;
229
		}
230
231 1
		static $subscription_addons;
232
233 1
		if ( is_null( $subscription_addons ) ) {
234
235 1
			$registered = GFAddon::get_registered_addons();
236
237 1
			foreach ( $registered as $addon ) {
238 1
				if ( method_exists( $addon, 'cancel_subscription' ) ) {
239 1
					$addon = $addon::get_instance();
240 1
					$subscription_addons[ $addon->get_slug() ] = $addon;
241
				}
242
			}
243
		}
244
245 1
		if ( empty( $subscription_addons ) ) {
246
			return $entry;
247
		}
248
249 1
		foreach ( $feeds as $slug => $feed_ids ) {
250
251 1
			if ( ! isset( $subscription_addons[ $slug ] ) ) {
252
				continue;
253
			}
254
255 1
			foreach ( $feed_ids as $feed_id ) {
256
257 1
				$feed = $subscription_addons[ $slug ]->get_feed( $feed_id );
258
259 1
				if ( $feed && 'subscription' === \GV\Utils::get( $feed, 'meta/transactionType' ) ) {
260
261 1
					if ( $subscription_addons[ $slug ]->cancel( $entry, $feed ) ) {
262
263 1
						$subscription_addons[ $slug ]->cancel_subscription( $entry, $feed );
264
265 1
						return \GFAPI::get_entry( $entry['id'] );
266
					}
267
				}
268
			}
269
		}
270
271
		return $entry;
272
	}
273
}
274
275
new GravityView_Field_Unsubscribe;
276