WordPress_GitHub_Sync_Response::success()   B
last analyzed

Complexity

Conditions 5
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5.9256

Importance

Changes 0
Metric Value
cc 5
eloc 5
nc 2
nop 1
dl 0
loc 9
ccs 4
cts 6
cp 0.6667
crap 5.9256
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Response management object.
4
 * @package WordPress_GitHub_Sync
5
 */
6
7
/**
8
 * Class WordPress_GitHub_Sync_Response
9
 */
10
class WordPress_GitHub_Sync_Response {
11
12
	/**
13
	 * Application container.
14
	 *
15
	 * @var WordPress_GitHub_Sync
16
	 */
17
	protected $app;
18
19
	/**
20
	 * WordPress_GitHub_Sync_Response constructor.
21
	 *
22
	 * @param WordPress_GitHub_Sync $app Application container.
23
	 */
24 2
	public function __construct( WordPress_GitHub_Sync $app ) {
25 2
		$this->app = $app;
26 2
	}
27
28
	/**
29
	 * Writes to the log and returns the error response.
30
	 *
31
	 * @param WP_Error $error Error to respond with.
32
	 *
33
	 * @return false
34
	 */
35 1
	public function error( WP_Error $error ) {
36 1
		global $wp_version;
37
38 1
		$this->log( $error );
39
40 1
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX && defined( 'WPGHS_AJAX' ) && WPGHS_AJAX ) {
41
			/**
42
			 * WordPress 4.1.0 introduced allowing WP_Error objects to be
43
			 * passed directly into `wp_send_json_error`. This shims in
44
			 * compatibility for older versions. We're currently supporting 3.9+.
45
			 */
46
			if ( version_compare( $wp_version, '4.1.0', '<' ) ) {
47
				$result = array();
48
49
				foreach ( $error->errors as $code => $messages ) {
50
					foreach ( $messages as $message ) {
51
						$result[] = array( 'code' => $code, 'message' => $message );
52
					}
53
				}
54
55
				$error = $result;
56
			}
57
58
			wp_send_json_error( $error );
59
		}
60
61 1
		return false;
62
	}
63
64
	/**
65
	 * Writes to the log and returns the success response.
66
	 *
67
	 * @param string $success Success message to respond with.
68
	 *
69
	 * @return true
70
	 */
71 1
	public function success( $success ) {
72 1
		$this->log( $success );
73
74 1
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX && defined( 'WPGHS_AJAX' ) && WPGHS_AJAX ) {
75
			wp_send_json_success( $success );
76
		}
77
78 1
		return true;
79
	}
80
81
	/**
82
	 * Writes a log message.
83
	 *
84
	 * Can extract a message from WP_Error object.
85
	 *
86
	 * @param string|WP_Error $msg Message to log.
87
	 */
88 2
	protected function log( $msg ) {
89 2
		if ( is_wp_error( $msg ) ) {
90 1
			$msg = $msg->get_error_message();
91 1
		}
92
93 2
		WordPress_GitHub_Sync::write_log( $msg );
94 2
	}
95
}
96