Passed
Push — master ( 84a9ea...46c2a9 )
by Atanas
01:31
created

ErrorHandler::getResponse()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 4
nop 1
dl 0
loc 22
ccs 7
cts 7
cp 1
crap 4
rs 8.9197
c 0
b 0
f 0
1
<?php
2
3
namespace WPEmerge\Exceptions;
4
5
use Exception as PhpException;
6
use Psr\Http\Message\ResponseInterface;
7
use Whoops\RunInterface;
8
use WPEmerge\Facades\Response;
9
10
class ErrorHandler implements ErrorHandlerInterface {
11
	/**
12
	 * Pretty handler.
13
	 *
14
	 * @var RunInterface|null
15
	 */
16
	protected $whoops = null;
17
18
	/**
19
	 * Whether debug mode is enabled.
20
	 *
21
	 * @var boolean
22
	 */
23
	protected $debug = false;
24
25
	/**
26
	 * Constructor.
27
	 *
28
	 * @codeCoverageIgnore
29
	 * @param RunInterface|null $stack_trace_handler
30
	 * @param boolean           $debug
31
	 */
32
	public function __construct( $whoops, $debug = false ) {
33
		$this->whoops = $whoops;
34
		$this->debug = $debug;
35
	}
36
37
	/**
38
	 * {@inheritDoc}
39
	 * @codeCoverageIgnore
40
	 */
41
	public function register() {
42
		if ( $this->whoops instanceof RunInterface ) {
43
			$this->whoops->register();
44
		}
45
	}
46
47
	/**
48
	 * {@inheritDoc}
49
	 * @codeCoverageIgnore
50
	 */
51
	public function unregister() {
52
		if ( $this->whoops instanceof RunInterface ) {
53
			$this->whoops->unregister();
54
		}
55
	}
56
57
	/**
58
	 * Convert an exception to a ResponseInterface instance if possible.
59
	 * Return the original exception if unsupported.
60
	 *
61
	 * @param  PhpException $exception
62
	 * @return mixed
63
	 */
64
	protected function toResponse( $exception ) {
65
		// @codeCoverageIgnoreStart
66
		if ( $exception instanceof InvalidCsrfTokenException ) {
67
			wp_nonce_ays( '' );
68
		}
69
		// @codeCoverageIgnoreEnd
70
71
		if ( $exception instanceof NotFoundException ) {
72
			return Response::error( 404 );
73
		}
74
75
		return $exception;
76
	}
77
78
	/**
79
	 * {@inheritDoc}
80
	 */
81 3
	public function getResponse( PhpException $exception ) {
82 3
		$response = $this->toResponse( $exception );
83
84 3
		if ( $response instanceof ResponseInterface ) {
85 1
			return $response;
86
		}
87
88 2
		if ( ! $this->debug ) {
89 1
			return Response::error( 500 );
90
		}
91
92
		// @codeCoverageIgnoreStart
93
		if ( $this->whoops instanceof RunInterface ) {
94
			$method = RunInterface::EXCEPTION_HANDLER;
95
			ob_start();
96
			$this->whoops->$method( $exception );
97
			$response = ob_get_clean();
98
			return Response::output( $response )->withStatus( 500 );
99
		}
100
		// @codeCoverageIgnoreEnd
101
102 1
		throw $exception;
103
	}
104
}
105