Passed
Push — master ( 534e7b...378b8e )
by Atanas
02:01
created

HttpKernel::filterTemplateInclude()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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