Completed
Push — staging ( 78e662...0f9e2f )
by
unknown
05:16
created

sendUpdateProfileEmail()   F

Complexity

Conditions 26
Paths 3724

Size

Total Lines 154

Duplication

Lines 24
Ratio 15.58 %

Code Coverage

Tests 0
CRAP Score 702

Importance

Changes 0
Metric Value
cc 26
nc 3724
nop 0
dl 24
loc 154
ccs 0
cts 96
cp 0
crap 702
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
class YIKES_Inc_Easy_Mailchimp_Public_Ajax {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
4
5
	/**
6
	 * Thetext domain of this plugin
7
	 *
8
	 * @since    1.0.0
9
	 * @access   private
10
	 * @var      string    $version    Used for internationalization
11
	 */
12
	public function __construct() {
13
		// ajax process form submission
14
		add_action( 'wp_ajax_nopriv_process_form_submission', array( $this , 'process_form_submission' ), 10 );
15
		add_action( 'wp_ajax_process_form_submission', array( $this , 'process_form_submission' ), 10 );
16
17
		// ajax send update emails
18
		add_action( 'wp_ajax_nopriv_easy_forms_send_email', array( $this , 'sendUpdateProfileEmail' ), 10 );
19
		add_action( 'wp_ajax_easy_forms_send_email', array( $this , 'sendUpdateProfileEmail' ), 10 );
20
21
		// increase submission count for a given form on successful submit
22
		add_action( 'wp_ajax_nopriv_increase_submission_count' , array( $this , 'increase_submission_count' ), 10 );
23
		add_action( 'wp_ajax_increase_submission_count' , array( $this , 'increase_submission_count' ), 10 );
24
	}
25
26
	/*
27
	*	Process form submisssions sent via ajax from the front end
28
	*	$form_data - serialized form data submitted
29
	*/
30
	public function process_form_submission() {
31
		// include our ajax processing file
32
		include_once( YIKES_MC_PATH . 'public/partials/shortcodes/process/process_form_submission_ajax.php' );
33
		exit();
34
	}
35
36
	/**
37
	 * Increase the submission count for a given form.
38
	 */
39
	public function increase_submission_count() {
40
		$form_id   = intval( $_POST['form_id'] );
41
		$interface = yikes_easy_mailchimp_extender_get_form_interface();
42
		$form      = $interface->get_form( $form_id );
43
44
		// If we don't have a form to update, just bail.
45
		if ( empty( $form ) ) {
46
			exit();
47
		}
48
49
		// Update the form.
50
		$submission_count = isset( $form['submissions'] ) ? $form['submissions'] + 1 : 1;
51
		$interface->update_form_field( $form_id, 'submissions', $submission_count );
52
53
		exit();
54
	}
55
56
	/*
57
		Send Update Profile Email
58
		@since v6.0.4.1
59
	*/
60
	public function sendUpdateProfileEmail() {
61
		$user_email    = filter_var( $_POST['user_email'], FILTER_SANITIZE_STRING );
62
		$user_id       = md5( $user_email );
63
		$list_id       = filter_var( $_POST['list_id'], FILTER_SANITIZE_STRING );
64
		$form_id       = filter_var( $_POST['form_id'], FILTER_SANITIZE_NUMBER_INT );
65
		$page_id       = filter_var( $_POST['page_id'], FILTER_SANITIZE_NUMBER_INT );
66
		$full_site_url = get_bloginfo( 'url' );
0 ignored issues
show
Unused Code introduced by
$full_site_url 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...
67
		$manager       = yikes_get_mc_api_manager();
68
69
		// Possibly handle errors.
70
		$errors   = array();
71
		$is_error = false;
72
73
		// List details API call.
74
		$list_details = $manager->get_list_handler()->get_list( $list_id );
75 View Code Duplication
		if ( is_wp_error( $list_details ) ) {
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...
76
			$error_logging = new Yikes_Inc_Easy_Mailchimp_Error_Logging();
77
			$error_logging->maybe_write_to_log( $list_details->get_error_code(),
78
				__( 'Send Update Profile Email - Get Account Lists', 'yikes-inc-easy-mailchimp-extender' ),
79
				'class.public_ajax.php'
80
			);
81
			$is_error = true;
82
			$errors[] = $list_details->get_error_message();
83
		}
84
85
		// Subscriber details API call.
86
		$subscriber_account_details = $manager->get_list_handler()->get_member( $list_id, $user_id );
87 View Code Duplication
		if ( is_wp_error( $subscriber_account_details ) ) {
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...
88
			$error_logging = new Yikes_Inc_Easy_Mailchimp_Error_Logging();
89
			$error_logging->maybe_write_to_log( $subscriber_account_details->get_error_code(), __( 'Send Update Profile Email - Get Member Info.', 'yikes-inc-easy-mailchimp-extender' ), 'class.public_ajax.php' );
90
			$is_error = true;
91
			$errors[] = $subscriber_account_details->get_error_message();
92
		}
93
94
		// Form details API call.
95
		$interface = yikes_easy_mailchimp_extender_get_form_interface();
96
		if ( ! empty( $interface ) && method_exists( $interface, 'get_form' ) && ! empty( $form_id ) ) {
97
			$form_data = $interface->get_form( $form_id );
98
			if ( ! empty( $form_data ) ) {
99
				if ( isset( $form_data['error_messages'] ) ) {
100
101
					if ( isset( $form_data['error_messages']['email-body'] ) && ! empty( $form_data['error_messages']['email-body'] ) ) {
102
						$email_body = apply_filters( 'the_content', $form_data['error_messages']['email-body'] );
103
					}
104
105 View Code Duplication
					if ( isset( $form_data['error_messages']['email-subject'] ) && ! empty( $form_data['error_messages']['email-subject'] ) ) {
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...
106
						$email_subject = $form_data['error_messages']['email-subject'];
107
					}
108
109 View Code Duplication
					if ( isset( $form_data['error_messages']['update-email-success'] ) && ! empty( $form_data['error_messages']['update-email-success'] ) ) {
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...
110
						$update_email_success_message = $form_data['error_messages']['update-email-success'];
111
					}
112
113 View Code Duplication
					if ( isset( $form_data['error_messages']['update-email-failure'] ) && ! empty( $form_data['error_messages']['update-email-failure'] ) ) {
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...
114
						$update_email_failed_message = $form_data['error_messages']['update-email-failure'];
115
					}
116
				}
117
			}
118
		}
119
120
		// Check for errors in any of the calls.
121
		if ( $is_error ) {
122
			$error_message = '<br>' . join( '<br>', $errors );
123
			/* translators: the placeholder is a string of errors returned from Mailchimp. */
124
			$error_message = sprintf( __( 'Error sending update profile email. <strong>Error(s): %s</strong>. Please contact the site administrator.', 'yikes-inc-easy-mailchimp-extender' ), $error_message );
125
			wp_send_json_error(
126
				array(
127
					'response_text' => '<div class="yikes-easy-mc-error-message">&#10005; ' . $error_message . '</div>',
128
				)
129
			);
130
131
			return;
132
		}
133
134
		// Construct the headers & email message content.
135
		$subscriber_id    = $subscriber_account_details['unique_email_id'];
136
		$update_link_href = str_replace( '/subscribe', '/profile', $list_details['subscribe_url_long'] );
137
		$update_link_href = add_query_arg( 'e', $subscriber_id, $update_link_href );
138
		$update_link_tag  = '<a href="' . $update_link_href . '">';
139
		$headers          = 'From: ' . $list_details['campaign_defaults']['from_name'] . ' <' . $list_details['campaign_defaults']['from_email'] . '>' . "\r\n";
140
		$headers         .= 'Content-type: text/html';
141
142
		if ( ! isset( $email_subject ) ) {
143
			$email_subject = __( 'Mailchimp Profile Update', 'yikes-inc-easy-mailchimp-extender' );
144
		}
145
146
		// Check if the email_body was set.
147
		if ( ! isset( $email_body ) || empty( $email_body ) ) {
148
149
			// The email_body should always be set, but we've made this function static just in case so we can grab our default.
150
			$email_body = Yikes_Inc_Easy_Mailchimp_Forms_Admin::generate_default_email_body();
151
		}
152
153
		if ( ! isset( $update_email_success_message ) ) {
154
			/* translators: the placeholder is a unicode checkmark */
155
			$update_email_success_message = sprintf( __( '%s Update email successfully sent. Please check your inbox for the message.', 'yikes-inc-easy-mailchimp-extender' ), '&#10004;' );
156
		}
157
158
		if ( ! isset( $update_email_failed_message ) ) {
159
			/* translators: the placeholder is a unicode X */
160
			$update_email_failed_message = sprintf( __( '%s Email failed to send. Please contact the site administrator.', 'yikes-inc-easy-mailchimp-extender' ), '&#10005;' );
161
		}
162
163
		/* Run our replacement strings for the email body. */
164
165
		// We let the user use [link] text [/link] for the update profile link so replace [link] with the <a> tag.
166
		$email_body = str_replace( array( '[link]', '[LINK]' ), $update_link_tag, $email_body );
167
168
		// And replace [/link] with the closing </a> tag.
169
		$email_body = str_replace( array( '[/link]', '[/LINK]' ), '</a>', $email_body );
170
171
		// We let the user use [url] for their website so replace [url] with get_home_url().
172
		$email_body = str_replace( array( '[url]', '[URL]' ), get_home_url(), $email_body );
173
174
		// We let the user use [email] for the subscriber's email so replace [email] with the subscriber's email.
175
		$email_body = str_replace( array( '[email]', '[EMAIL]' ), $user_email, $email_body );
176
177
		// We let the user use [subscriber_id] for the subscriber's unique email ID so replace [subscriber_id] with the subscriber's unique email ID.
178
		$email_body = str_replace( array( '[subscriber_id]', '[SUBSCRIBER_ID]' ), $subscriber_id, $email_body );
179
180
		// We let the user use [form_name] for the form's name so replace [form_name] with the form's name.
181
		$email_body = str_replace( array( '[form_name]', '[FORM_NAME]' ), $form_data['form_name'], $email_body );
0 ignored issues
show
Bug introduced by
The variable $form_data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
182
183
		// We let the user use [fname] and [lname] so replace those.
184
		$email_body = str_replace( array( '[fname]', '[FNAME]' ), isset( $subscriber_account_details['merge_fields']['FNAME'] ) ? $subscriber_account_details['merge_fields']['FNAME'] : '', $email_body );
185
		$email_body = str_replace( array( '[lname]', '[LNAME]' ), isset( $subscriber_account_details['merge_fields']['LNAME'] ) ? $subscriber_account_details['merge_fields']['LNAME'] : '', $email_body );
186
187
		/* Confirm that the email was sent */
188
		if ( wp_mail( $user_email, apply_filters( 'yikes-mailchimp-update-email-subject', $email_subject ), apply_filters( 'yikes-mailchimp-update-email-content', $email_body, $update_link_href ), $headers ) ) {
189
190
			$update_email_success_message = apply_filters( 'yikes-mailchimp-update-email-success-message', $update_email_success_message, $form_id, $user_email );
191
			$submission_settings          = isset( $form_data['submission_settings'] ) ? $form_data['submission_settings'] : null;
192
			$redirect_settings            = Yikes_Inc_Easy_Mailchimp_Extender_Process_Submission_Handler::handle_submission_response_success_redirect( $form_id, $submission_settings, $page_id );
193
194
			wp_send_json_success(
195
				array(
196
					'response_text'  => '<div class="yikes-easy-mc-success-message">' . $update_email_success_message . '</div>',
197
					'redirection'    => $redirect_settings['redirection'],
198
					'redirect'       => $redirect_settings['redirect'],
199
					'redirect_timer' => $redirect_settings['redirect_timer'],
200
					'new_window'     => $redirect_settings['new_window'],
201
				)
202
			);
203
		} else {
204
205
			$update_email_failed_message = apply_filters( 'yikes-mailchimp-update-email-failed-message', $update_email_failed_message, $form_id, $user_email );
206
207
			wp_send_json_error(
208
				array(
209
					'response_text' => '<div class="yikes-easy-mc-error-message">' . $update_email_failed_message . '</div>',
210
				)
211
			);
212
		}
213
	}
214
}
215