WordPressController   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 17
dl 0
loc 47
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A handle() 0 22 5
1
<?php /**
2
 * @package   WPEmerge
3
 * @author    Atanas Angelov <[email protected]>
4
 * @copyright 2017-2019 Atanas Angelov
5
 * @license   https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0
6
 * @link      https://wpemerge.com/
7
 */ /** @noinspection PhpUnusedParameterInspection */
8
namespace WPEmerge\Controllers;
9
10
use Psr\Http\Message\ResponseInterface;
11
use WPEmerge\Exceptions\ConfigurationException;
12
use WPEmerge\Requests\RequestInterface;
13
use WPEmerge\View\ViewService;
14
15
/**
16
 * Handles normal WordPress requests without interfering
17
 * Useful if you only want to add a middleware to a route without handling the output
18
 *
19
 * @codeCoverageIgnore
20
 */
21
class WordPressController {
22
	/**
23
	 * View service.
24
	 *
25
	 * @var ViewService
26
	 */
27
	protected $view_service = null;
28
29
	/**
30
	 * Constructor.
31
	 *
32
	 * @codeCoverageIgnore
33
	 * @param ViewService $view_service
34
	 */
35
	public function __construct( ViewService $view_service ) {
36
		$this->view_service = $view_service;
37
	}
38
39
	/**
40
	 * Default WordPress handler.
41
	 *
42
	 * @param  RequestInterface  $request
43
	 * @param  string            $view
44
	 * @return ResponseInterface
45
	 */
46
	public function handle( RequestInterface $request, $view = '' ) {
47
		if ( is_admin() || wp_doing_ajax() ) {
48
			throw new ConfigurationException(
49
				'Attempted to run the default WordPress controller on an ' .
50
				'admin or AJAX page. Did you miss to specify a custom handler for ' .
51
				'a route or accidentally used \App::route()->all() during admin ' .
52
				'requests?'
53
			);
54
		}
55
56
		if ( empty( $view ) ) {
57
			throw new ConfigurationException(
58
				'No view loaded for default WordPress controller. ' .
59
				'Did you miss to specify a custom handler for an ajax or admin route?'
60
			);
61
		}
62
63
		$status_code = http_response_code();
64
65
		return $this->view_service->make( $view )
66
			->toResponse()
67
			->withStatus( is_int( $status_code ) ? $status_code : 200 );
68
	}
69
}
70