Writing_On_GitHub_Response::error()   B
last analyzed

Complexity

Conditions 8
Paths 3

Size

Total Lines 27
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 11
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 27
ccs 0
cts 16
cp 0
crap 72
rs 8.4444
1
<?php
2
/**
3
 * Response management object.
4
 * @package Writing_On_GitHub
5
 */
6
7
/**
8
 * Class Writing_On_GitHub_Response
9
 */
10
class Writing_On_GitHub_Response {
11
12
    /**
13
     * Application container.
14
     *
15
     * @var Writing_On_GitHub
16
     */
17
    protected $app;
18
19
    /**
20
     * Writing_On_GitHub_Response constructor.
21
     *
22
     * @param Writing_On_GitHub $app Application container.
23
     */
24
    public function __construct( Writing_On_GitHub $app ) {
25
        $this->app = $app;
26
    }
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
    public function error( WP_Error $error ) {
36
        global $wp_version;
37
38
        $this->log( $error );
39
40
        if ( defined( 'DOING_AJAX' ) && DOING_AJAX && defined( 'WOGH_AJAX' ) && WOGH_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
        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
    public function success( $success ) {
72
        $this->log( $success );
73
74
        if ( defined( 'DOING_AJAX' ) && DOING_AJAX && defined( 'WOGH_AJAX' ) && WOGH_AJAX ) {
75
            wp_send_json_success( $success );
76
        }
77
78
        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
    protected function log( $msg ) {
89
        if ( is_wp_error( $msg ) ) {
90
            $msg = $msg->get_error_message();
91
        }
92
93
        Writing_On_GitHub::write_log( $msg );
94
    }
95
}
96