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

RouteHandler::getResponse()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 4
nop 1
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace WPEmerge\Routing;
4
5
use Exception;
6
use Psr\Http\Message\ResponseInterface;
7
use WPEmerge\Facades\Response;
8
use WPEmerge\Helpers\Handler;
9
use WPEmerge\Responses\ResponsableInterface;
10
11
/**
12
 * Represent a Closure or a controller method to be executed in response to a request
13
 */
14
class RouteHandler {
15
	/**
16
	 * Actual handler
17
	 *
18
	 * @var Handler
19
	 */
20
	protected $handler = null;
21
22
	/**
23
	 * Constructor
24
	 *
25
	 * @param string|\Closure $handler
26
	 */
27 1
	public function __construct( $handler ) {
28 1
		$this->handler = new Handler( $handler );
29 1
	}
30
31
	/**
32
	 * Get the handler
33
	 *
34
	 * @return Handler
35
	 */
36 1
	public function get() {
37 1
		return $this->handler;
38
	}
39
40
	/**
41
	 * Convert a user returned response to a ResponseInterface instance if possible.
42
	 * Return the original value if unsupported.
43
	 *
44
	 * @param  mixed $response
45
	 * @return mixed
46
	 */
47 4
	protected function getResponse( $response ) {
48 4
		if ( is_string( $response ) ) {
49 1
			return Response::output( $response );
50
		}
51
52 3
		if ( is_array( $response ) ) {
53 1
			return Response::json( $response );
54
		}
55
56 2
		if ( $response instanceof ResponsableInterface ) {
57 1
			return $response->toResponse();
58
		}
59
60 1
		return $response;
61
	}
62
63
	/**
64
	 * Execute the handler
65
	 *
66
	 * @throws Exception
67
	 * @param  mixed             $arguments,...
68
	 * @return ResponseInterface
69
	 */
70 5
	public function execute() {
71 5
		$response = call_user_func_array( [$this->handler, 'execute'], func_get_args() );
72 5
		$response = $this->getResponse( $response );
73
74 5
		if ( ! $response instanceof ResponseInterface ) {
75 1
			throw new Exception( 'Response returned by controller is not valid (expected ' . ResponseInterface::class . '; received ' . gettype( $response ) . ').' );
76
		}
77
78 4
		return $response;
79
	}
80
}
81