Passed
Push — ci ( c52b9f...7698af )
by litefeel
02:24
created

Writing_On_GitHub_Database::save_posts()   C

Complexity

Conditions 11
Paths 50

Size

Total Lines 65
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
dl 0
loc 65
ccs 0
cts 41
cp 0
rs 5.9999
c 0
b 0
f 0
cc 11
eloc 37
nc 50
nop 1
crap 132

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
 * Database interface.
4
 * @package Writing_On_GitHub
5
 */
6
7
/**
8
 * Class Writing_On_GitHub_Database
9
 */
10
class Writing_On_GitHub_Database {
0 ignored issues
show
Complexity introduced by
This class has a complexity of 68 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
Coding Style introduced by
The class Writing_On_GitHub_Database is not named in CamelCase.

This check marks class names that have not been written in CamelCase.

In CamelCase names are written without any punctuation, the start of each new word being marked by a capital letter. The whole name starts with a capital letter as well.

Thus the name database connector becomes DatabaseConnector.

Loading history...
Coding Style introduced by
The property $whitelisted_post_types is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $whitelisted_post_statuses is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
11
12
	/**
13
	 * Application container.
14
	 *
15
	 * @var Writing_On_GitHub
16
	 */
17
	protected $app;
18
19
	/**
20
	 * Currently whitelisted post types.
21
	 *
22
	 * @var array
23
	 */
24
	protected $whitelisted_post_types = array( 'post', 'page' );
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $whitelisted_post_types exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
25
26
	/**
27
	 * Currently whitelisted post statuses.
28
	 *
29
	 * @var array
30
	 */
31
	protected $whitelisted_post_statuses = array( 'publish' );
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $whitelisted_post_statuses exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
32
33
	/**
34
	 * Instantiates a new Database object.
35
	 *
36
	 * @param Writing_On_GitHub $app Application container.
37
	 */
38
	public function __construct( Writing_On_GitHub $app ) {
39
		$this->app = $app;
40
	}
41
42
	/**
43
	 * Queries the database for all of the supported posts.
44
	 *
45
     * @param  bool $force
46
     * @return Writing_On_GitHub_Post[]|WP_Error
0 ignored issues
show
Documentation introduced by
Should the return type not be WP_Error|array? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
47
     */
48
	public function fetch_all_supported( $force = false ) {
0 ignored issues
show
Coding Style Naming introduced by
The method fetch_all_supported is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_ids is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
49
		$args  = array(
50
			'post_type'   => $this->get_whitelisted_post_types(),
51
			'post_status' => $this->get_whitelisted_post_statuses(),
52
			'nopaging'    => true,
0 ignored issues
show
introduced by
Disabling pagination is prohibited in VIP context, do not set nopaging to true ever.
Loading history...
53
			'fields'      => 'ids',
54
		);
55
56
		$query = new WP_Query( apply_filters( 'wogh_pre_fetch_all_supported', $args ) );
57
58
		$post_ids = $query->get_posts();
59
60
		if ( ! $post_ids ) {
61
			return new WP_Error(
62
				'no_results',
63
				__( 'Querying for supported posts returned no results.', 'writing-on-github' )
64
			);
65
		}
66
67
		$results = array();
68
		foreach ( $post_ids as $post_id ) {
69
			// Do not export posts that have already been exported
70
			if ( $force || ! get_post_meta( $post_id, '_wogh_sha', true ) ||
71
				 ! get_post_meta( $post_id, '_wogh_github_path', true) ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
72
73
				$results[] = new Writing_On_GitHub_Post( $post_id, $this->app->api() );
74
			}
75
		}
76
77
		return $results;
78
	}
79
80
	/**
81
	 * Queries a post and returns it if it's supported.
82
	 *
83
	 * @param int $post_id Post ID to fetch.
84
	 *
85
	 * @return WP_Error|Writing_On_GitHub_Post
86
	 */
87
	public function fetch_by_id( $post_id ) {
0 ignored issues
show
Coding Style Naming introduced by
The method fetch_by_id is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The parameter $post_id is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
88
		$post = new Writing_On_GitHub_Post( $post_id, $this->app->api() );
89
90
		if ( ! $this->is_post_supported( $post ) ) {
91
			return new WP_Error(
92
				'unsupported_post',
93
				sprintf(
94
					__(
95
						'Post ID %s is not supported by WOGH. See wiki to find out how to add support.',
96
						'writing-on-github'
97
					),
98
					$post_id
99
				)
100
			);
101
		}
102
103
		return $post;
104
	}
105
106
	/**
107
	 * Saves an array of Post objects to the database
108
	 * and associates their author as well as their latest
109
	 *
110
	 * @param Writing_On_GitHub_Post[] $posts Array of Posts to save.
111
	 * @param string                       $email Author email.
0 ignored issues
show
Bug introduced by
There is no parameter named $email. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
112
	 *
113
	 * @return string|WP_Error
114
	 */
115
	public function save_posts( array $posts ) {
0 ignored issues
show
Complexity introduced by
This operation has 962 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

You can also find more information in the “Code” section of your repository.

Loading history...
Coding Style Naming introduced by
The method save_posts is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $user_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
116
117
		/**
118
		 * Whether an error has occurred.
119
		 *
120
		 * @var WP_Error|false $error
121
		 */
122
		$error = false;
123
124
		foreach ( $posts as $post ) {
125
			$args = apply_filters( 'wogh_pre_import_args', $this->post_args( $post ), $post );
126
127
			remove_filter('content_save_pre', 'wp_filter_post_kses');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
128
			$post_id = $post->is_new() ?
129
				wp_insert_post( $args, true ) :
130
				wp_update_post( $args, true );
131
			add_filter('content_save_pre', 'wp_filter_post_kses');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
132
133
			if ( is_wp_error( $post_id ) ) {
134
				if ( ! $error ) {
135
					$error = $post_id;
136
				} else {
137
					$error->add( $post_id->get_error_code(), $post_id->get_error_message() );
138
				}
139
140
				// Abort saving if updating the post fails.
141
				continue;
142
			}
143
144
			// $this->set_revision_author( $post_id, $user_id );
145
146
			if ( $post->is_new() ) {
147
				$author = false;
148
				$meta = $post->get_meta();
149
				if ( ! empty( $meta ) && ! empty( $meta['author'] ) ) {
150
					$author = $meta['author'];
151
				}
152
				$user    = $this->fetch_commit_user( $author );
153
				$user_id = ! is_wp_error( $user ) ? $user->ID : 0;
154
				$this->set_post_author( $post_id, $user_id );
155
			}
156
157
			$post->set_post( get_post( $post_id ) );
158
159
			$meta = apply_filters( 'wogh_pre_import_meta', $post->get_meta(), $post );
160
161
			unset( $meta['tags'] );
162
			unset( $meta['categories'] );
163
			unset( $meta['author'] );
164
			unset( $meta['post_date'] );
165
			unset( $meta['post_excerpt'] );
166
			unset( $meta['permalink'] );
167
			unset( $meta['link'] );
168
169
			foreach ( $meta as $key => $value ) {
170
				update_post_meta( $post_id, $key, $value );
171
			}
172
		}
173
174
		if ( $error ) {
175
			return $error;
176
		}
177
178
		return __( 'Successfully saved posts.', 'writing-on-github' );
179
	}
180
181
	protected function post_args( $post ) {
0 ignored issues
show
Coding Style Naming introduced by
The method post_args is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
182
		$args = $post->get_args();
183
		$meta = $post->get_meta();
184
185
		// prevent backslash loss
186
		$args['post_content'] = addslashes($args['post_content']);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
187
188
		// update tags
189
		if ( isset( $meta['tags'] ) && $meta['tags'] ) {
190
		    $args['tags_input'] = $meta['tags'];
191
		}
192
193
		// update categories
194
		if ( isset( $meta['categories'] ) && $meta['categories'] ) {
195
		    $categories = $meta['categories'];
196
		    if (!is_array($categories)) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
Expected 1 space before "!"; 0 found
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
197
		        $categories = array($categories);
0 ignored issues
show
introduced by
No space after opening parenthesis of array is bad style
Loading history...
introduced by
No space before closing parenthesis of array is bad style
Loading history...
198
		    }
199
		    $terms = get_terms(array(
200
		        'taxonomy' => 'category',
201
		        'fields' => 'id=>name',
202
		        'hide_empty' => 0,
203
		        'name' => $categories
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
204
		        )
205
		    );
206
		    $map = array();
207
		    foreach ($categories as $name) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
208
		        $map[$name] = 1;
0 ignored issues
show
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
209
		    }
210
211
		    $ids = array();
212
		    if (!empty($terms)) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
Expected 1 space before "!"; 0 found
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
213
		        foreach ($terms as $id => $name) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
214
		            $ids[] = $id;
215
		            unset($map[$name]);
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
Array keys should be surrounded by spaces unless they contain a string or an integer.
Loading history...
216
		        }
217
		    }
218
219
		    // create new terms
220
		    if (!empty($map)) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
Expected 1 space before "!"; 0 found
Loading history...
introduced by
Expected 1 space after "!"; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
221
		        foreach ($map as $name => $value) {
0 ignored issues
show
introduced by
No space after opening parenthesis is prohibited
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
222
		            $term = wp_insert_term($name, 'category', array('parent' => 0));
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
introduced by
No space after opening parenthesis of array is bad style
Loading history...
introduced by
No space before closing parenthesis of array is bad style
Loading history...
223
		            // array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id);
224
		            $ids[] = $term['term_id'];
225
		        }
226
		    }
227
228
		    $args['post_category'] = $ids;
229
		}
230
231
		return $args;
232
	}
233
234
	/**
235
	 * Deletes a post from the database based on its GitHub path.
236
	 *
237
	 * @param string $path Path of Post to delete.
238
	 *
239
	 * @return string|WP_Error
240
	 */
241
	public function delete_post_by_path( $path ) {
0 ignored issues
show
Coding Style Naming introduced by
The method delete_post_by_path is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
242
		$query = new WP_Query( array(
243
			'meta_key'       => '_wogh_github_path',
0 ignored issues
show
introduced by
Detected usage of meta_key, possible slow query.
Loading history...
244
			'meta_value'     => $path,
0 ignored issues
show
introduced by
Detected usage of meta_value, possible slow query.
Loading history...
245
			'meta_compare'   => '=',
246
			'posts_per_page' => 1,
247
			'fields'         => 'ids',
248
		) );
249
250
		$post_id = $query->get_posts();
251
		$post_id = array_pop( $post_id );
252
253
		if ( ! $post_id ) {
254
			$parts     = explode( '/', $path );
255
			$filename  = array_pop( $parts );
256
			$directory = $parts ? array_shift( $parts ) : '';
257
258 View Code Duplication
			if ( false !== strpos( $directory, 'post' ) ) {
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...
259
				preg_match( '/([0-9]{4})-([0-9]{2})-([0-9]{2})-(.*)\.md/', $filename, $matches );
260
				$title = $matches[4];
261
262
				$query = new WP_Query( array(
263
					'name'     => $title,
264
					'posts_per_page' => 1,
265
					'post_type' => $this->get_whitelisted_post_types(),
266
					'fields'         => 'ids',
267
				) );
268
269
				$post_id = $query->get_posts();
270
				$post_id = array_pop( $post_id );
271
			}
272
273 View Code Duplication
			if ( ! $post_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...
274
				preg_match( '/(.*)\.md/', $filename, $matches );
275
				$title = $matches[1];
276
277
				$query = new WP_Query( array(
278
					'name'     => $title,
279
					'posts_per_page' => 1,
280
					'post_type' => $this->get_whitelisted_post_types(),
281
					'fields'         => 'ids',
282
				) );
283
284
				$post_id = $query->get_posts();
285
				$post_id = array_pop( $post_id );
286
			}
287
		}
288
289
		if ( ! $post_id ) {
290
			return new WP_Error(
291
				'path_not_found',
292
				sprintf(
293
					__( 'Post not found for path %s.', 'writing-on-github' ),
294
					$path
295
				)
296
			);
297
		}
298
299
		$result = wp_delete_post( $post_id );
300
301
		// If deleting fails...
302 View Code Duplication
		if ( false === $result ) {
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...
303
			$post = get_post( $post_id );
304
305
			// ...and the post both exists and isn't in the trash...
306
			if ( $post && 'trash' !== $post->post_status ) {
307
				// ... then something went wrong.
308
				return new WP_Error(
309
					'db_error',
310
					sprintf(
311
						__( 'Failed to delete post ID %d.', 'writing-on-github' ),
312
						$post_id
313
					)
314
				);
315
			}
316
		}
317
318
		return sprintf(
319
			__( 'Successfully deleted post ID %d.', 'writing-on-github' ),
320
			$post_id
321
		);
322
	}
323
324
	public function delete_post( $post_id ) {
0 ignored issues
show
Coding Style Naming introduced by
The method delete_post is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The parameter $post_id is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
325
		$result = wp_delete_post( $post_id );
326
327
		// If deleting fails...
328 View Code Duplication
		if ( false === $result ) {
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...
329
			$post = get_post( $post_id );
330
331
			// ...and the post both exists and isn't in the trash...
332
			if ( $post && 'trash' !== $post->post_status ) {
333
				// ... then something went wrong.
334
				return new WP_Error(
335
					'db_error',
336
					sprintf(
337
						__( 'Failed to delete post ID %d.', 'writing-on-github' ),
338
						$post_id
339
					)
340
				);
341
			}
342
		}
343
344
		return sprintf(
345
			__( 'Successfully deleted post ID %d.', 'writing-on-github' ),
346
			$post_id
347
		);
348
	}
349
350
	/**
351
	 * Returns the list of post type permitted.
352
	 *
353
	 * @return array
354
	 */
355
	protected function get_whitelisted_post_types() {
0 ignored issues
show
Coding Style Naming introduced by
The method get_whitelisted_post_types is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
356
		return apply_filters( 'wogh_whitelisted_post_types', $this->whitelisted_post_types );
357
	}
358
359
	/**
360
	 * Returns the list of post status permitted.
361
	 *
362
	 * @return array
363
	 */
364
	protected function get_whitelisted_post_statuses() {
0 ignored issues
show
Coding Style Naming introduced by
The method get_whitelisted_post_statuses is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
365
		return apply_filters( 'wogh_whitelisted_post_statuses', $this->whitelisted_post_statuses );
366
	}
367
368
	/**
369
	 * Formats a whitelist array for a query.
370
	 *
371
	 * @param array $whitelist Whitelisted posts to format into query.
372
	 *
373
	 * @return string Whitelist formatted for query
374
	 */
375
	protected function format_for_query( $whitelist ) {
0 ignored issues
show
Coding Style Naming introduced by
The method format_for_query is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
376
		foreach ( $whitelist as $key => $value ) {
377
			$whitelist[ $key ] = "'$value'";
378
		}
379
380
		return implode( ', ', $whitelist );
381
	}
382
383
	/**
384
	 * Verifies that both the post's status & type
385
	 * are currently whitelisted
386
	 *
387
	 * @param  Writing_On_GitHub_Post $post Post to verify.
388
	 *
389
	 * @return boolean                          True if supported, false if not.
390
	 */
391
	protected function is_post_supported( Writing_On_GitHub_Post $post ) {
0 ignored issues
show
Coding Style Naming introduced by
The method is_post_supported is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
392
		if ( wp_is_post_revision( $post->id ) ) {
393
			return false;
394
		}
395
396
		// We need to allow trashed posts to be queried, but they are not whitelisted for export.
397
		if ( ! in_array( $post->status(), $this->get_whitelisted_post_statuses() ) && 'trash' !== $post->status() ) {
398
			return false;
399
		}
400
401
		if ( ! in_array( $post->type(), $this->get_whitelisted_post_types() ) ) {
402
			return false;
403
		}
404
405
		if ( $post->has_password() ) {
406
			return false;
407
		}
408
409
		return apply_filters( 'wogh_is_post_supported', true, $post );
410
	}
411
412
	/**
413
	 * Retrieves the commit user for a provided display name
414
	 *
415
	 * Searches for a user with provided display name or returns
416
	 * the default user saved in the database.
417
	 *
418
	 * @param string $display_name User display name to search for.
419
	 *
420
	 * @return WP_Error|WP_User
421
	 */
422
	protected function fetch_commit_user( $display_name ) {
0 ignored issues
show
Coding Style Naming introduced by
The method fetch_commit_user is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The parameter $display_name is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $display_name is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $search_string is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
423
		// If we can't find a user and a default hasn't been set,
424
		// we're just going to set the revision author to 0.
425
		$user = false;
426
427
		if ( ! empty( $display_name ) ) {
428
			$search_string = esc_attr( $display_name );
429
			$query = new WP_User_Query( array(
430
			    'search'         => "{$search_string}",
431
			    'search_columns' => array(
432
			        'display_name',
433
			        'user_nicename',
434
			        'user_login',
435
			    )
436
			) );
437
			$users = $query->get_results();
438
			$user = empty($users) ? false : $users[0];
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
439
		}
440
441
		if ( ! $user ) {
442
			// Use the default user.
443
			$user = get_user_by( 'id', (int) get_option( 'wogh_default_user' ) );
444
		}
445
446
		if ( ! $user ) {
447
			return new WP_Error(
448
				'user_not_found',
449
				sprintf(
450
					__( 'Commit user not found for email %s', 'writing-on-github' ),
451
					$email
452
				)
453
			);
454
		}
455
456
		return $user;
457
	}
458
459
	/**
460
	 * Sets the author latest revision
461
	 * of the provided post ID to the provided user.
462
	 *
463
	 * @param int $post_id Post ID to update revision author.
464
	 * @param int $user_id User ID for revision author.
465
	 *
466
	 * @return string|WP_Error
467
	 */
468
	protected function set_revision_author( $post_id, $user_id ) {
0 ignored issues
show
Coding Style Naming introduced by
The method set_revision_author is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The parameter $post_id is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The parameter $user_id is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $new_revision is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $user_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
469
		$revision = wp_get_post_revisions( $post_id );
470
471
		if ( ! $revision ) {
472
			$new_revision = wp_save_post_revision( $post_id );
473
474
			if ( ! $new_revision || is_wp_error( $new_revision ) ) {
475
				return new WP_Error( 'db_error', 'There was a problem saving a new revision.' );
476
			}
477
478
			// `wp_save_post_revision` returns the ID, whereas `get_post_revision` returns the whole object
479
			// in order to be consistent, let's make sure we have the whole object before continuing.
480
			$revision = get_post( $new_revision );
481
482
			if ( ! $revision ) {
483
				return new WP_Error( 'db_error', 'There was a problem retrieving the newly recreated revision.' );
484
			}
485
		} else {
486
			$revision = array_shift( $revision );
487
		}
488
489
		return $this->set_post_author( $revision->ID, $user_id );
490
	}
491
492
	/**
493
	 * Updates the user ID for the provided post ID.
494
	 *
495
	 * Bypassing triggering any hooks, including creating new revisions.
496
	 *
497
	 * @param int $post_id Post ID to update.
498
	 * @param int $user_id User ID to update to.
499
	 *
500
	 * @return string|WP_Error
501
	 */
502
	protected function set_post_author( $post_id, $user_id ) {
0 ignored issues
show
Coding Style Naming introduced by
The method set_post_author is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The parameter $post_id is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The parameter $user_id is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $user_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style Naming introduced by
The variable $post_id is not named in camelCase.

This check marks variable names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
503
		global $wpdb;
504
505
		$result = $wpdb->update(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
506
			$wpdb->posts,
507
			array(
508
				'post_author' => (int) $user_id,
509
			),
510
			array(
511
				'ID' => (int) $post_id,
512
			),
513
			array( '%d' ),
514
			array( '%d' )
515
		);
516
517
		if ( false === $result ) {
518
			return new WP_Error( 'db_error', $wpdb->last_error );
519
		}
520
521
		if ( 0 === $result ) {
522
			return sprintf(
523
				__( 'No change for post ID %d.', 'writing-on-github' ),
524
				$post_id
525
			);
526
		}
527
528
		clean_post_cache( $post_id );
529
530
		return sprintf(
531
			__( 'Successfully updated post ID %d.', 'writing-on-github' ),
532
			$post_id
533
		);
534
	}
535
536
	/**
537
	 * Update the provided post's blob sha.
538
	 *
539
	 * @param Writing_On_GitHub_Post $post Post to update.
540
	 * @param string                     $sha Sha to update to.
541
	 *
542
	 * @return bool|int
543
	 */
544
	public function set_post_sha( $post, $sha ) {
0 ignored issues
show
Coding Style Naming introduced by
The method set_post_sha is not named in camelCase.

This check marks method names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
545
		return update_post_meta( $post->id, '_wogh_sha', $sha );
546
	}
547
}
548