Passed
Push — master ( ba86e8...c40970 )
by Atanas
01:50
created

WordPressController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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