Passed
Push — master ( 8b88ad...5ac4fd )
by Atanas
01:43
created

ErrorHandler::toResponse()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 4
nop 1
dl 0
loc 12
ccs 4
cts 4
cp 1
crap 3
rs 9.4285
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
	 *
60
	 * @param  PhpException            $exception
61
	 * @return ResponseInterface|false
62
	 */
63 2
	protected function toResponse( $exception ) {
64
		// @codeCoverageIgnoreStart
65
		if ( $exception instanceof InvalidCsrfTokenException ) {
66
			wp_nonce_ays( '' );
67
		}
68
		// @codeCoverageIgnoreEnd
69
70 2
		if ( $exception instanceof NotFoundException ) {
71 1
			return Response::error( 404 );
72
		}
73
74 1
		return false;
75
	}
76
77
	/**
78
	 * Convert an exception to a pretty error response.
79
	 *
80
	 * @codeCoverageIgnore
81
	 * @param  PhpException      $exception
82
	 * @return ResponseInterface
83
	 */
84
	protected function toPrettyErrorResponse( $exception ) {
85
		$method = RunInterface::EXCEPTION_HANDLER;
86
		ob_start();
87
		$this->whoops->$method( $exception );
88
		$response = ob_get_clean();
89
		return Response::output( $response )->withStatus( 500 );
90
	}
91
92
	/**
93
	 * {@inheritDoc}
94
	 */
95 3
	public function getResponse( PhpException $exception ) {
96 3
		$response = $this->toResponse( $exception );
97
98 3
		if ( $response !== false ) {
99 1
			return $response;
100
		}
101
102 2
		if ( ! $this->debug ) {
103 1
			return Response::error( 500 );
104
		}
105
106 1
		if ( $this->whoops instanceof RunInterface ) {
107
			return $this->toPrettyErrorResponse( $exception );
108
		}
109
110 1
		throw $exception;
111
	}
112
}
113