Passed
Branch master (5de32f)
by Atanas
01:39
created

HttpKernel::getAdminHook()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 1
dl 0
loc 13
ccs 0
cts 11
cp 0
crap 20
rs 9.9666
c 0
b 0
f 0
1
<?php
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\Kernels;
11
12
use Exception;
13
use Psr\Http\Message\ResponseInterface;
14
use WPEmerge\Application\Application;
15
use WPEmerge\Exceptions\ErrorHandlerInterface;
16
use WPEmerge\Facades\Response;
17
use WPEmerge\Middleware\HasMiddlewareDefinitionsTrait;
18
use WPEmerge\Requests\RequestInterface;
19
use WPEmerge\Routing\HasQueryFilterInterface;
20
use WPEmerge\Routing\Pipeline;
21
use WPEmerge\Routing\Router;
22
use WPEmerge\Routing\SortsMiddlewareTrait;
23
24
/**
25
 * Describes how a request is handled.
26
 */
27
class HttpKernel implements HttpKernelInterface {
28
	use HasMiddlewareDefinitionsTrait;
29
	use SortsMiddlewareTrait;
30
31
	/**
32
	 * Application.
33
	 *
34
	 * @var Application
35
	 */
36
	protected $app = null;
37
38
	/**
39
	 * Request.
40
	 *
41
	 * @var RequestInterface
42
	 */
43
	protected $request = null;
44
45
	/**
46
	 * Router.
47
	 *
48
	 * @var Router
49
	 */
50
	protected $router = null;
51
52
	/**
53
	 * Error handler.
54
	 *
55
	 * @var ErrorHandlerInterface
56
	 */
57
	protected $error_handler = null;
58
59
	/**
60
	 * Constructor.
61
	 *
62
	 * @codeCoverageIgnore
63
	 * @param Application           $app
64
	 * @param RequestInterface      $request
65
	 * @param Router                $router
66
	 * @param ErrorHandlerInterface $error_handler
67
	 */
68
	public function __construct( Application $app, RequestInterface $request, Router $router, ErrorHandlerInterface $error_handler ) {
69
		$this->app = $app;
70
		$this->request = $request;
71
		$this->router = $router;
72
		$this->error_handler = $error_handler;
73
	}
74
75
	/**
76
	 * {@inheritDoc}
77
	 * @codeCoverageIgnore
78
	 */
79
	public function bootstrap() {
80
		// Web.
81
		add_action( 'request', [$this, 'filterRequest'], 1000 );
82
		add_action( 'template_include', [$this, 'filterTemplateInclude'], 1000 );
83
84
		// Ajax.
85
		add_action( 'admin_init', [$this, 'registerAjaxAction'] );
86
87
		// Admin.
88
		add_action( 'admin_init', [$this, 'registerAdminAction'] );
89
	}
90
91
	/**
92
	 * {@inheritDoc}
93
	 */
94 2
	public function handle( RequestInterface $request, $arguments = [] ) {
95 2
		$route = $this->router->execute( $request );
96
97 2
		if ( $route === null ) {
98 1
			return null;
99
		}
100
101 1
		$handler = function () use ( $route ) {
102 1
			$arguments = func_get_args();
103 1
			$request = array_shift( $arguments );
104 1
			return call_user_func( [$route, 'handle'], $request, $arguments );
105 1
		};
106
107 1
		$response = $this->run( $request, $route->getMiddleware(), $handler, $arguments );
108
109 1
		$container = $this->app->getContainer();
110 1
		$container[ WPEMERGE_RESPONSE_KEY ] = $response;
111
112 1
		return $response;
113
	}
114
115
	/**
116
	 * {@inheritDoc}
117
	 */
118 2
	public function run( RequestInterface $request, $middleware, $handler, $arguments = [] ) {
119 2
		$this->error_handler->register();
120
121
		try {
122 2
			$middleware = $this->expandMiddleware( $middleware );
123 2
			$middleware = $this->uniqueMiddleware( $middleware );
124 2
			$middleware = $this->sortMiddleware( $middleware );
125
126 2
			$response = ( new Pipeline() )
127 2
				->pipe( $middleware )
128 2
				->to( $handler )
129 2
				->run( $request, array_merge( [$request], $arguments ) );
130 2
		} catch ( Exception $exception ) {
131 1
			$response = $this->error_handler->getResponse( $request, $exception );
132
		}
133
134 1
		$this->error_handler->unregister();
135
136 1
		return $response;
137
	}
138
139
	/**
140
	 * Filter the main query vars.
141
	 *
142
	 * @param  array $query_vars
143
	 * @return array
144
	 */
145 2
	public function filterRequest( $query_vars ) {
146
		/** @var $routes \WPEmerge\Routing\RouteInterface[] */
147 2
		$routes = $this->router->getRoutes();
148
149 2
		foreach ( $routes as $route ) {
150 2
			if ( ! $route instanceof HasQueryFilterInterface ) {
151 2
				continue;
152
			}
153
154 2
			if ( ! $route->isSatisfied( $this->request ) ) {
155 1
				continue;
156
			}
157
158 2
			$query_vars = $route->applyQueryFilter( $this->request, $query_vars );
159 2
			break;
160 2
		}
161
162 2
		return $query_vars;
163
	}
164
165
	/**
166
	 * Filter the main template file.
167
	 *
168
	 * @param  string $view
169
	 * @return string
170
	 */
171 3
	public function filterTemplateInclude( $view ) {
172
		/** @var $wp_query \WP_Query */
173 3
		global $wp_query;
174
175 3
		$response = $this->handle( $this->request, [$view] );
176
177 3
		if ( $response instanceof ResponseInterface ) {
178 2
			if ( $response->getStatusCode() === 404 ) {
179 1
				$wp_query->set_404();
180 1
			}
181
182 2
			return WPEMERGE_DIR . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'view.php';
183
		}
184
185 1
		return $view;
186
	}
187
188
	/**
189
	 * Register ajax action to hook into current one.
190
	 *
191
	 * @return void
192
	 */
193
	public function registerAjaxAction() {
194
		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) {
195
			return;
196
		}
197
198
		$action = $this->request->post( 'action', $this->request->get( 'action' ) );
199
		$action = sanitize_text_field( $action );
200
201
		add_action( "wp_ajax_{$action}", [$this, 'actionAjax'] );
202
		add_action( "wp_ajax_nopriv_{$action}", [$this, 'actionAjax'] );
203
	}
204
205
	/**
206
	 * Act on ajax action.
207
	 *
208
	 * @return void
209
	 */
210
	public function actionAjax() {
211
		$response = $this->handle( $this->request, [''] );
212
213
		if ( ! $response instanceof ResponseInterface ) {
214
			return;
215
		}
216
217
		Response::respond( $response );
218
		wp_die( '', '', ['response' => null] );
219
	}
220
221
	/**
222
	 * Get page hook.
223
	 * Slightly modified version of code from wp-admin/admin.php.
224
	 *
225
	 * @return string
226
	 */
227
	protected function getAdminPageHook() {
228
		global $pagenow, $typenow, $plugin_page;
229
230
		$page_hook = '';
231
		if ( isset( $plugin_page ) ) {
232
			if ( ! empty( $typenow ) ) {
233
				$the_parent = $pagenow . '?post_type=' . $typenow;
234
			} else {
235
				$the_parent = $pagenow;
236
			}
237
238
			$page_hook = get_plugin_page_hook( $plugin_page, $the_parent );
239
		}
240
241
		return $page_hook;
242
	}
243
244
	/**
245
	 * Get admin page hook.
246
	 * Slightly modified version of code from wp-admin/admin.php.
247
	 *
248
	 * @param  string $page_hook
249
	 * @return string
250
	 */
251
	protected function getAdminHook( $page_hook ) {
252
		global $pagenow, $plugin_page;
253
254
		$hook_suffix = '';
255
		if ( ! empty( $page_hook ) ) {
256
			$hook_suffix = $page_hook;
257
		} else if ( isset( $plugin_page ) ) {
258
			$hook_suffix = $plugin_page;
259
		} else if ( isset( $pagenow ) ) {
260
			$hook_suffix = $pagenow;
261
		}
262
263
		return $hook_suffix;
264
	}
265
266
	/**
267
	 * Register admin action to hook into current one.
268
	 *
269
	 * @return void
270
	 */
271
	public function registerAdminAction() {
272
		global $pagenow;
273
274
		if ( $pagenow !== 'admin.php' ) {
275
			return;
276
		}
277
278
		$page_hook = $this->getAdminPageHook();
279
		$hook_suffix = $this->getAdminHook( $page_hook );
280
281
		add_action( "load-{$hook_suffix}", [$this, 'actionAdminLoad'] );
282
		add_action( $hook_suffix, [$this, 'actionAdmin'] );
283
	}
284
285
	/**
286
	 * Act on admin action load.
287
	 *
288
	 * @return void
289
	 */
290
	public function actionAdminLoad() {
291
		$response = $this->handle( $this->request, [''] );
292
293
		if ( ! $response instanceof ResponseInterface ) {
294
			return;
295
		}
296
297
		if ( ! headers_sent() ) {
298
			Response::sendHeaders( $response );
299
		}
300
	}
301
302
	/**
303
	 * Act on admin action.
304
	 *
305
	 * @return void
306
	 */
307
	public function actionAdmin() {
308
		$response = $this->app->resolve( WPEMERGE_RESPONSE_KEY );
309
310
		if ( $response === null ) {
311
			return;
312
		}
313
314
		Response::sendBody( $response );
315
	}
316
}
317