Passed
Push — master ( f6ffce...df97a7 )
by Andrey
01:35
created

Rest_Api_Handler::isRestRequest()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 5
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 12
rs 8.8571
1
<?php
2
namespace Rarst\wps;
3
4
use Whoops\Exception\Formatter;
5
use Whoops\Handler\Handler;
6
use Whoops\Handler\JsonResponseHandler;
7
use Whoops\Util\Misc;
8
9
/**
10
 * WordPress-specific version of Json handler for REST API.
11
 */
12
class Rest_Api_Handler extends JsonResponseHandler {
13
14
	/**
15
	 * @return bool
16
	 */
17
	private function isRestRequest() {
1 ignored issue
show
Coding Style introduced by
isRestRequest uses the super-global variable $_SERVER 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...
18
19
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
20
			return true;
21
		}
22
23
		// This is dirty, but no better way to detect before parse_request.
24
		if ( ! empty( $_SERVER['REQUEST_URI'] ) && 0 !== stripos( $_SERVER['REQUEST_URI'], rest_get_url_prefix() ) ) {
25
			return true;
26
		}
27
28
		return false;
29
	}
30
31
	/**
32
	 * @return int
33
	 */
34
	public function handle() {
35
36
		if ( ! $this->isRestRequest() ) {
37
			return Handler::DONE;
38
		}
39
40
		$data     = Formatter::formatExceptionAsDataArray( $this->getInspector(), $this->addTraceToOutput() );
41
		$response = array(
42
			'code'    => $data['type'],
43
			'message' => $data['message'],
44
			'data'    => $data,
45
		);
46
47
		if ( Misc::canSendHeaders() ) {
48
			status_header( 500 );
49
			header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
50
		}
51
52
		$json_options = version_compare( PHP_VERSION, '5.4.0', '>=' ) ? JSON_PRETTY_PRINT : 0;
53
54
		echo wp_json_encode( $response, $json_options );
55
56
		return Handler::QUIT;
57
	}
58
}
59