Bulk_Actions::custom_bulk_action()   C
last analyzed

Complexity

Conditions 7
Paths 12

Size

Total Lines 68
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 35
nc 12
nop 0
dl 0
loc 68
rs 6.9654
c 0
b 0
f 0

How to fix   Long Method   

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
 * Admin Bulk Actions
4
 *
5
 * Add bulk actions to post types edit screens.
6
 * Based on https://github.com/Seravo/wp-custom-bulk-actions
7
 *
8
 * @package SimpleCalendar/Admin
9
 */
10
namespace SimpleCalendar\Admin;
11
12
if ( ! defined( 'ABSPATH' ) ) {
13
	exit;
14
}
15
16
/**
17
 * Admin bulk actions.
18
 */
19
class Bulk_Actions {
20
21
	/**
22
	 * Target post type.
23
	 *
24
	 * @access public
25
	 * @var string
26
	 */
27
	public $bulk_action_post_type = '';
28
29
	/**
30
	 * Bulk actions.
31
	 *
32
	 * @access private
33
	 * @var array
34
	 */
35
	private $actions = array();
36
37
	/**
38
	 * Constructor.
39
	 *
40
	 * @since 3.0.0
41
	 *
42
	 * @param string $post_type
43
	 */
44
	public function __construct( $post_type ) {
45
		$this->bulk_action_post_type = post_type_exists( $post_type ) ? $post_type : '';
46
	}
47
48
	/**
49
	 * Define all your custom bulk actions and corresponding callbacks
50
	 * Define at least $menu_text and $callback parameters
51
	 *
52
	 * @since 3.0.0
53
	 *
54
	 * @param array $args
55
	 */
56
	public function register_bulk_action( $args ) {
57
58
		$func = array();
59
		$func['action_name']  = isset( $args['action_name'] )  ? sanitize_key( $args['action_name'] ) : '';
60
		$func['callback']     = isset( $args['callback'] )     ? $args['callback'] : '';
61
		$func['menu_text']    = isset( $args['menu_text'] )    ? esc_attr( $args['menu_text'] ) : '';
62
		$func['admin_notice'] = isset( $args['admin_notice'] ) ? esc_attr( $args['admin_notice'] ) : '';
63
64
		if ( $func['action_name'] && $func['callback'] ) {
65
			$this->actions[ $func['action_name'] ] = $func;
66
		}
67
	}
68
69
	/**
70
	 * Init.
71
	 *
72
	 * Callbacks need to be registered before add_actions.
73
	 *
74
	 * @since 3.0.0
75
	 */
76
	public function init() {
77
		if ( is_admin() ) {
78
			add_action( 'admin_footer-edit.php', array( $this, 'custom_bulk_admin_footer' ) );
79
			add_action( 'load-edit.php',         array( $this, 'custom_bulk_action' ) );
80
			add_action( 'admin_notices',         array( $this, 'custom_bulk_admin_notices' ) );
81
		}
82
	}
83
84
	/**
85
	 * Step 1: add the custom Bulk Action to the select menus.
86
	 *
87
	 * @since 3.0.0
88
	 */
89
	public function custom_bulk_admin_footer() {
90
91
		global $post_type;
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...
92
93
		// Only permit actions with defined post type.
94
		if ( $post_type == $this->bulk_action_post_type ) {
95
96
			?>
97
			<script type="text/javascript">
98
				jQuery( document ).ready( function() {
99
					<?php foreach ( $this->actions as $action_name => $action ) : ?>
100
						jQuery( '<option>' ).val( '<?php echo $action_name ?>' ).text( '<?php echo $action['menu_text'] ?>').appendTo( 'select[name="action"]'  );
101
						jQuery( '<option>' ).val( '<?php echo $action_name ?>' ).text( '<?php echo $action['menu_text'] ?>').appendTo( 'select[name="action2"]' );
102
					<?php endforeach; ?>
103
				} );
104
			</script>
105
			<?php
106
107
		}
108
109
	}
110
111
	/**
112
	 * Step 2: handle the custom Bulk Action.
113
	 *
114
	 * Based on the post http://wordpress.stackexchange.com/questions/29822/custom-bulk-action
115
	 *
116
	 * @since 3.0.0
117
	 */
118
	public function custom_bulk_action() {
0 ignored issues
show
Coding Style introduced by
custom_bulk_action uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
119
120
		global $typenow;
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...
121
		$post_type = $typenow;
122
123
		if ( $post_type == $this->bulk_action_post_type ) {
124
125
			// Get the action.
126
			// Depending on your resource type this could be WP_Users_List_Table, WP_Comments_List_Table, etc.
127
			$wp_list_table = _get_list_table( 'WP_Posts_List_Table' );
128
			$action = $wp_list_table->current_action();
129
130
			// Allow only defined actions.
131
			$allowed_actions = array_keys( $this->actions );
132
			if ( ! in_array( $action, $allowed_actions ) ) {
133
				return;
134
			}
135
136
			// Security check.
137
			check_admin_referer( 'bulk-posts' );
138
139
			// Make sure ids are submitted.
140
			// Depending on the resource type, this may be 'media' or 'ids'.
141
			if ( isset( $_REQUEST['post'] ) ) {
142
				$post_ids = array_map( 'intval', $_REQUEST['post'] );
143
			}
144
145
			if ( empty( $post_ids ) ) {
146
				return;
147
			}
148
149
			// This is based on wp-admin/edit.php.
150
			$sendback = remove_query_arg(
151
				array( 'exported', 'untrashed', 'deleted', 'ids' ),
152
				wp_get_referer()
153
			);
154
			if ( ! $sendback ) {
155
				$sendback = admin_url( "edit.php?post_type=$post_type" );
156
			}
157
158
			$pagenum  = $wp_list_table->get_pagenum();
159
			$sendback = add_query_arg( 'paged', $pagenum, $sendback );
160
161
			// Check that we have anonymous function as a callback.
162
			$anon_fns = array_filter( $this->actions[ $action ], function( $el ) {
163
				return $el instanceof \Closure;
164
			} );
165
166
			if ( count( $anon_fns ) > 0 ) {
167
				$this->actions[ $action ]['callback']( $post_ids );
168
			} else {
169
				call_user_func( $this->actions[ $action ]['callback'], $post_ids );
170
			}
171
172
			$sendback = add_query_arg(
173
				array( 'success_action' => $action, 'ids' => join( ',', $post_ids ) ),
174
				$sendback
175
			);
176
			$sendback = remove_query_arg(
177
				array( 'action', 'paged', 'mode', 'action2', 'tags_input', 'post_author', 'comment_status', 'ping_status', '_status', 'post', 'bulk_edit', 'post_view' ),
178
				$sendback
179
			);
180
181
			wp_redirect( $sendback );
182
183
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method custom_bulk_action() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
184
		}
185
	}
186
187
	/**
188
	 * Step 3: display an admin notice after action.
189
	 *
190
	 * @since 3.0.0
191
	 */
192
	public function custom_bulk_admin_notices() {
0 ignored issues
show
Coding Style introduced by
custom_bulk_admin_notices uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
193
194
		global $post_type, $pagenow;
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...
195
196
		if ( isset( $_REQUEST['ids'] ) ) {
197
			$post_ids = explode( ',', $_REQUEST['ids'] );
198
		}
199
200
		// Make sure ids are submitted.
201
		// Depending on the resource type, this may be 'media' or 'ids'.
202
		if ( empty( $post_ids ) ) {
203
			return;
204
		}
205
206
		$post_ids_count = is_array( $post_ids ) ? count( $post_ids ) : 1;
207
208
		if ( $pagenow == 'edit.php' && $post_type == $this->bulk_action_post_type ) {
209
210
			if ( isset( $_REQUEST['success_action'] ) ) {
211
212
				// Print notice in admin bar.
213
				$message = $this->actions[ $_REQUEST['success_action'] ]['admin_notice'];
214
215
				if ( is_array( $message ) ) {
216
					$message = sprintf( _n( $message['single'], $message['plural'], $post_ids_count, 'google-calendar-events' ), $post_ids_count );
217
				}
218
219
				$class = 'updated notice is-dismissible above-h2';
220
				if ( ! empty( $message ) ) {
221
					echo "<div class=\"{$class}\"><p>{$message}</p></div>";
222
				}
223
			}
224
		}
225
	}
226
227
}
228