Completed
Push — master ( 2f95aa...1df65a )
by Evan
05:36
created

yikes-mailchimp-subscriber-count.php ➔ yikes_mailchimp_subscriber_count_shortcode()   F

Complexity

Conditions 20
Paths 378

Size

Total Lines 96
Code Lines 53

Duplication

Lines 6
Ratio 6.25 %

Code Coverage

Tests 0
CRAP Score 420

Importance

Changes 0
Metric Value
cc 20
eloc 53
c 0
b 0
f 0
nc 378
nop 1
dl 6
loc 96
ccs 0
cts 56
cp 0
crap 420
rs 3.6338

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 8 and the first side effect is on line 104.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/*
3
*	Shortcode to display subscriber counts for a given list
4
*	@usage	[yikes-mailchimp-subscriber-count list="list_id"]
5
*	@since v6.0.2.4
6
*/
7
8
function yikes_mailchimp_subscriber_count_shortcode( $attributes ) {
9
		
10
	// Attributes
11
	extract( shortcode_atts(
12
		array(
13
			'form' => '', // pass in a form, which will retreive the associated list ID -- takes precendence
14
			'list' => '', // pass in a specific list ID
15
		), $attributes , 'yikes-mailchimp-subscriber-count' )
16
	);
17
	
18
	/* If the user hasn't authenticated yet - bail */
19 View Code Duplication
	if( get_option( 'yikes-mc-api-validation' , 'invalid_api_key' ) != 'valid_api_key' ) {
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...
20
		if( WP_DEBUG ) {
21
			return '<strong>' . __( "You don't appear to be connected to MailChimp.", "yikes-inc-easy-mailchimp-extender" ) . '</strong>';
22
		} 
23
		return;
24
	}
25
	
26
	$form = ( ! empty( $attributes['form'] ) ) ? str_replace( '&quot;', '', $attributes['form'] ) : false; // replace the sanitize quotes to perform a proper query
27
	$list_id = ( ! empty( $attributes['list'] ) ) ? $attributes['list'] : false;
28
		
29
	/* If no list ID was passed into the shortcode - bail */
30
	if( ! $list_id  && ! $form) {
31
		if( WP_DEBUG ) {
32
			return '<strong>' . __( 'You forgot to include the list or form ID.', 'yikes-inc-easy-mailchimp-extender' ) . '</strong>';
33
		} 
34
		return;	
35
	}
36
37
	/* if a form ID and a list ID were passed in, use the form ID */
38
	if( ( $form ) || ( $form && $list_id ) ) {
39
		global $wpdb;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
40
		// return it as an array, so we can work with it to build our form below
41
		$form_results = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . 'yikes_easy_mc_forms WHERE id = ' . $form . '', ARRAY_A );
42
		// confirm we have some results, or return an error
43
		if( ! $form_results ) {
44
			if( WP_DEBUG ) {	
45
				return __( "Oh no...This form doesn't exist. Head back to the manage forms page and select a different form." , 'yikes-inc-easy-mailchimp-extender' );
46
			}
47
			return;
48
		}
49
		$form_data = $form_results[0];
50
		$list_id = sanitize_key( $form_data['list_id'] ); // associated list id (users who fill out the form will be subscribed to this list)
51
	}
52
	
53
	// object buffer 
54
	ob_start();	
55
	
56
	// submit the request the get the subscriber count
57
	try {
58
	
59
		// get the api key
60
		$api_key = trim( get_option( 'yikes-mc-api-key' , '' ) );
61
		$dash_position = strpos( $api_key, '-' );
62
		if( $dash_position !== false ) {
63
			$api_endpoint = 'https://' . substr( $api_key, $dash_position + 1 ) . '.api.mailchimp.com/2.0/lists/list.json';
64
		}
65
		
66
		// run the request
67
		$subscriber_count_response = wp_remote_post( $api_endpoint, array( 
68
			'body' => apply_filters( 'yikes-mailchimp-user-subscriber-count-api-request', array( 
69
				'apikey' => $api_key,
70
				'filters' => array(
71
					'list_id' => $list_id,
72
				),
73
			), $list_id ),
74
			'timeout' => 10,
75
			'sslverify' => apply_filters( 'yikes-mailchimp-sslverify', true )
76
		) );
77
		
78
		$subscriber_count_response = json_decode( wp_remote_retrieve_body( $subscriber_count_response ), true );
79
		if( isset( $subscriber_count_response['error'] ) ) {		
80
			if( WP_DEBUG || get_option( 'yikes-mailchimp-debug-status' , '' ) == '1' ) {
81
				require_once YIKES_MC_PATH . 'includes/error_log/class-yikes-inc-easy-mailchimp-error-logging.php';
82
				$error_logging = new Yikes_Inc_Easy_Mailchimp_Error_Logging();
83
				$error_logging->yikes_easy_mailchimp_write_to_error_log( $subscriber_count_response['error'], __( "Get Account Lists" , 'yikes-inc-easy-mailchimp-extender' ), "yikes-mailchimp-subscriber-count.php" );
84
			}
85
		}
86
		// if more than one list is returned, something went wrong - bail
87
		if( $subscriber_count_response['total'] != 1 ) {
88
			if( WP_DEBUG ) {
89
				return '<strong>' . sprintf( __( "It looks like this list wasn't found. Double check the list with with ID '%s' exists.", "yikes-inc-easy-mailchimp-extender" ), $list_id ) . '</strong>';
90
			} 
91
			return;
92
		}
93
				
94
		/* type cast the returned value as an integer */
95
		echo (int) apply_filters( 'yikes-mailchimp-subscriber-count-value', $subscriber_count_response['data'][0]['stats']['member_count'] );
96
		
97
	} catch ( Exception $error ) {
98
		echo $error->getMessage();
99
	}
100
	
101
	return ob_get_clean();
102
		
103
}
104
add_shortcode( 'yikes-mailchimp-subscriber-count', 'yikes_mailchimp_subscriber_count_shortcode' ); 
105
106
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...