User::get_roles()   B
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 3
nop 0
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
1
<?php
2
namespace DummyPress\Types;
3
use DummyPress as Main;
4
use DummyPress\TestContent as TestContent;
5
use DummyPress\Delete as Delete;
6
use DummyPress\Abstracts as Abs;
7
8
9
/**
10
 * Class to build test data for custom post types.
11
 *
12
 * @package    WordPress
13
 * @subpackage Evans
14
 * @author     Mike Selander
15
 */
16
class User extends Abs\Type {
17
18
	/**
19
	 * type
20
	 * Defines type slug for use elsewhere in the plugin
21
	 *
22
	 * @var string
23
	 * @access protected
24
	 */
25
	protected $type = 'user';
26
27
	/**
28
	 * Create test data posts.
29
	 *
30
	 * This is where the magic begins. We accept a cpt id (slug) and potntially
31
	 * a number of posts to create. We then fetch the supports & metaboxes
32
	 * for that cpt and feed them into a function to create each post individually.
33
	 *
34
	 * @access private
35
	 *
36
	 * @see $this->get_cpt_supports, $this->get_metaboxes, $this->create_test_object
37
	 *
38
	 * @param string $slug a custom post type ID.
39
	 * @param boolean $connection Whether or not we're connected to the Internet.
40
	 * @param int $num Optional. Number of posts to create.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $num not be string|integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
41
	 */
42 View Code Duplication
	public function create_objects( $slug, $connection, $num = '' ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
43
44
		// If we're missing a custom post type id - don't do anything
45
		if ( empty( $slug ) ) {
46
			return;
47
		}
48
49
		// Set our connection status for the rest of the methods
50
		$this->connected = $connection;
51
52
		// If we forgot to put in a quantity, make one for us
53
		if ( empty( $num ) ) {
54
			$num = rand( 5, 30 );
55
		}
56
57
		// Create test posts
58
		for( $i = 0; $i < $num; $i++ ) {
0 ignored issues
show
Unused Code introduced by
$i++; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
59
60
			$return = $this->create_test_object( $slug );
61
62
			return $return;
63
64
		}
65
66
	}
67
68
69
	/**
70
	 * Creates the individual test data user.
71
	 *
72
	 * Create individual posts for testing with. Gathers basic information such
73
	 * as title, content, thumbnail, etc. and inserts them with the post. Also
74
	 * adds metaboxes if applicable .
75
	 *
76
	 * @access private
77
	 *
78
	 * @see TestContent, wp_insert_post, add_post_meta, update_post_meta, $this->random_metabox_content
79
	 *
80
	 * @param string $slug a custom post type ID.
81
	 */
82
	private function create_test_object( $slug ) {
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
83
84
		if ( ! is_user_logged_in() ) {
85
			return false;
86
		}
87
88
		$name = apply_filters( "tc_{$slug}_user_name", TestContent::name() );
89
90
		// First, insert our post
91
		$userdata = array(
92
			'user_pass'			=> wp_generate_password( 12, true, true ),
93
			'user_login'		=> strtolower( $name['first'] . $name['last'] ) . rand( 10, 100 ),
94
			'user_email'		=> apply_filters( "tc_{$slug}_user_email", TestContent::email( true ) ),
95
			'display_name'		=> strtolower( $name['first'] . $name['last'] ),
96
			'first_name'		=> $name['first'],
97
			'last_name'			=> $name['last'],
98
			'description'		=> TestContent::title(),
99
			'user_registered'	=> date( 'Y-m-d H:i:s' ),
100
			'role'				=> $slug,
101
		);
102
103
		// Insert the user
104
		$user_id = wp_insert_user( apply_filters( "tc_{$slug}_user_arguments", $userdata ) );
105
106
		// Then, set a test content flag on the new post for later deletion
107
		add_user_meta( $user_id, 'dummypress_test_data', '__test__', true );
108
109
		// Check if we have errors and return them or created message
110 View Code Duplication
		if ( is_wp_error( $user_id ) ) {
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...
111
			error_log( $user_id->get_error_message() );
112
			return $user_id;
113
		} else {
114
			return array(
115
				'action'	=> 'created',
116
				'object'	=> 'user',
117
				'oid'		=> $user_id,
118
				'type'		=> $slug,
119
				'link_edit'	=> admin_url( '/user-edit.php?user_id=' . $user_id ),
120
				'link_view' => get_author_posts_url( $user_id )
121
			);
122
		}
123
124
	}
125
126
127
	/**
128
	 * Get all roles and set a cleaner array.
129
	 *
130
	 * @see get_editable_roles
131
	 *
132
	 * @global object $wp_roles WP Roles obbject
133
	 *
134
	 * @return array Array of roles for use in creation and deletion
135
	 */
136
	public function get_roles() {
137
		global $wp_roles;
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...
138
		$clean_roles = array();
139
140
	    $role_names = $wp_roles->get_names();
141
		$flipped = array_flip( $role_names );
142
143
		// Loop through all available roles
144
		$roles = get_editable_roles();
145
146
		$skipped_roles = array(
147
			'Administrator'
148
		);
149
150
		foreach ( $roles as $role ) {
151
152
			if ( in_array( $role['name'], $skipped_roles ) ) {
153
				continue;
154
			}
155
156
			$clean_roles[] = array(
157
				'name'	=> $role['name'],
158
				'slug'	=> $flipped[ $role['name'] ]
159
			);
160
161
		}
162
163
		return $clean_roles;
164
165
	}
166
167
168
	/**
169
	 * Delete all test data, regardless of type, within posts.
170
	 *
171
	 * @see Delete
172
	 */
173
	public function delete_all() {
174
175
		$delete =  new Delete;
176
177
		// Make sure that the current user is logged in & has full permissions.
178
		if ( ! $delete->user_can_delete() ) {
179
			return;
180
		}
181
182
		// Loop through all post types and remove any test data
183
		$post_types = get_post_types( array( 'public' => true ), 'objects' );
184
		foreach ( $post_types as $post_type ) :
185
186
		    $this->delete( $post_type->name );
187
188
		endforeach;
189
190
		// Loop through all user roles and remove any data
191
		foreach ( $this->get_roles() as $role ) :
192
193
			$this->delete( $role['slug'] );
194
195
		endforeach;
196
197
	}
198
199
200
	/**
201
	 * Delete test data users.
202
	 *
203
	 * This function will search for all posts of a particular post type ($slug)
204
	 * and delete them all using a particular cmb flag that we set when creating
205
	 * the posts. Validates the user first.
206
	 *
207
	 * @see WP_Query, wp_delete_post
208
	 *
209
	 * @param string $slug a custom post type ID.
210
	 */
211
	public function delete( $slug ) {
212
213
		$delete = new Delete;
214
215
		// Make sure that the current user is logged in & has full permissions.
216
		if ( ! $delete->user_can_delete() ) {
217
			return;
218
		}
219
220
		// Check that $cptslg has a string.
221
		if ( empty( $slug ) ) {
222
			return;
223
		}
224
225
		// Find our test data by the unique flag we set when we created the data
226
		$query = array(
227
			'role' 			=> $slug,
228
			'number'		=> 500,
229
			'meta_query' 	=> array(
230
				'relation'		=> 'OR',
231
		        array(
232
		           'key'       => 'dummypress_test_data',
233
		           'value'     => '__test__',
234
		           'compare'   => '='
235
			   ),
236
			   array(
237
				  'key'       => 'evans_test_content',
238
				  'value'     => '__test__',
239
				  'compare'   => '='
240
			  ),
241
			),
242
		);
243
244
		$objects = new \WP_User_Query( $query );
245
		$users	 = $objects->get_results();
246
247
		if ( ! empty( $users ) ) {
248
249
			$events = array();
250
251 View Code Duplication
			foreach ( $users as $user ) {
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...
252
253
				// Make sure we can't delete ourselves by accident
254
				if ( $user->ID == get_current_user_id() ) {
255
					continue;
256
				}
257
258
				// Double check our set user meta value
259
				if ( '__test__' != get_user_meta( $user->ID, 'dummypress_test_data', true ) && '__test__' != get_user_meta( $user->ID, 'evans_test_content', true ) ) {
260
					continue;
261
				}
262
263
				$events[] = array(
264
					'action'	=> 'deleted',
265
					'oid'		=> $user->ID,
266
					'type'		=> $slug,
267
					'link'		=> ''
268
				);
269
270
				// Force delete the user
271
				wp_delete_user( $user->ID );
272
273
			}
274
275
			$events[] = array(
276
				'action'	=> 'general',
277
				'message'	=> __( 'Deleted', 'dummybot' ) . ' ' . $slug
278
			);
279
280
			return $events;
281
282
		}
283
284
	}
285
286
}
287