Failed Conditions
Branch refactor/kernels (fbf61a)
by Atanas
01:47
created

src/Kernels/HttpKernel.php (1 issue)

Labels
Severity
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 RequestInterface      $request
64
	 * @param Router                $router
65
	 * @param ErrorHandlerInterface $error_handler
66
	 */
67
	public function __construct( Application $app, RequestInterface $request, Router $router, ErrorHandlerInterface $error_handler ) {
68
		$this->app = $app;
69
		$this->request = $request;
70
		$this->router = $router;
71
		$this->error_handler = $error_handler;
72
	}
73
74
	/**
75
	 * {@inheritDoc}
76
	 * @codeCoverageIgnore
77
	 */
78
	public function bootstrap() {
79
		// Web.
80
		add_action( 'request', [$this, 'filterRequest'], 1000 );
81
		add_action( 'template_include', [$this, 'filterTemplateInclude'], 1000 );
82
83
		// Ajax.
84
		add_action( 'admin_init', [$this, 'registerAjaxAction'] );
85
86
		// Admin.
87
		add_action( 'admin_init', [$this, 'registerAdminAction'] );
88
	}
89
90
	/**
91
	 * {@inheritDoc}
92
	 */
93 2
	public function handle( RequestInterface $request, $arguments = [] ) {
94 2
		$route = $this->router->execute( $request, $arguments );
95
96 2
		if ( $route === null ) {
97 1
			return null;
98
		}
99
100 1
		$handler = function () use ( $route ) {
101 1
			$arguments = func_get_args();
102 1
			$request = array_shift( $arguments );
103 1
			return call_user_func( [$route, 'handle'], $request, $arguments );
104 1
		};
105
106 1
		$response = $this->run( $request, $route->getMiddleware(), $handler, $arguments );
107
108 1
		$container = $this->app->getContainer();
109 1
		$container[ WPEMERGE_RESPONSE_KEY ] = $response;
110
111 1
		return $response;
112
	}
113
114
	/**
115
	 * {@inheritDoc}
116
	 */
117 2
	public function run( RequestInterface $request, $middleware, $handler, $arguments = [] ) {
118 2
		$this->error_handler->register();
119
120
		try {
121 2
			$middleware = $this->expandMiddleware( $middleware );
122 2
			$middleware = $this->uniqueMiddleware( $middleware );
0 ignored issues
show
$middleware of type array<mixed,array> is incompatible with the type string[] expected by parameter $middleware of WPEmerge\Kernels\HttpKernel::uniqueMiddleware(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

122
			$middleware = $this->uniqueMiddleware( /** @scrutinizer ignore-type */ $middleware );
Loading history...
123 2
			$middleware = $this->sortMiddleware( $middleware );
124
125 2
			$response = ( new Pipeline() )
126 2
				->middleware( $middleware )
127 2
				->to( $handler )
128 2
				->run( $request, array_merge( [$request], $arguments ) );
129 2
		} catch ( Exception $exception ) {
130 1
			$response = $this->error_handler->getResponse( $request, $exception );
131
		}
132
133 1
		$this->error_handler->unregister();
134
135 1
		return $response;
136
	}
137
138
	/**
139
	 * Filter the main query vars.
140
	 *
141
	 * @param  array $query_vars
142
	 * @return array
143
	 */
144 2
	public function filterRequest( $query_vars ) {
145 2
		$routes = $this->router->getRoutes();
146
147 2
		foreach ( $routes as $route ) {
148 2
			if ( ! $route instanceof HasQueryFilterInterface ) {
149 2
				continue;
150
			}
151
152 2
			if ( ! $route->isSatisfied( $this->request ) ) {
153 1
				continue;
154
			}
155
156 2
			$query_vars = $route->applyQueryFilter( $this->request, $query_vars );
157 2
			break;
158 2
		}
159
160 2
		return $query_vars;
161
	}
162
163
	/**
164
	 * Filter the main template file.
165
	 *
166
	 * @param  string $view
167
	 * @return string
168
	 */
169 3
	public function filterTemplateInclude( $view ) {
170 3
		global $wp_query;
171
172 3
		$response = $this->handle( $this->request, [$view] );
173
174 3
		if ( $response instanceof ResponseInterface ) {
175 2
			if ( $response->getStatusCode() === 404 ) {
176 1
				$wp_query->set_404();
177 1
			}
178
179 2
			return WPEMERGE_DIR . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'view.php';
180
		}
181
182 1
		return $view;
183
	}
184
185
	/**
186
	 * Register ajax action to hook into current one.
187
	 *
188
	 * @return void
189
	 */
190
	public function registerAjaxAction() {
191
		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) {
192
			return;
193
		}
194
195
		$action = $this->request->post( 'action', $this->request->get( 'action' ) );
196
		$action = sanitize_text_field( $action );
197
198
		add_action( "wp_ajax_{$action}", [$this, 'actionAjax'] );
199
		add_action( "wp_ajax_nopriv_{$action}", [$this, 'actionAjax'] );
200
	}
201
202
	/**
203
	 * Act on ajax action.
204
	 *
205
	 * @return void
206
	 */
207
	public function actionAjax() {
208
		$response = $this->handle( $this->request, [''] );
209
210
		if ( ! $response instanceof ResponseInterface ) {
211
			return;
212
		}
213
214
		Response::respond( $response );
215
		wp_die( '', '', ['response' => null] );
216
	}
217
218
	/**
219
	 * Get page hook.
220
	 * Slightly modified version of code from wp-admin/admin.php.
221
	 *
222
	 * @param  string $page_hook
223
	 * @return string
224
	 */
225
	protected function getAdminPageHook() {
226
		global $pagenow, $typenow, $plugin_page;
227
228
		$page_hook = '';
229
		if ( isset( $plugin_page ) ) {
230
			if ( ! empty( $typenow ) ) {
231
				$the_parent = $pagenow . '?post_type=' . $typenow;
232
			} else {
233
				$the_parent = $pagenow;
234
			}
235
236
			$page_hook = get_plugin_page_hook( $plugin_page, $the_parent );
237
		}
238
239
		return $page_hook;
240
	}
241
242
	/**
243
	 * Get admin page hook.
244
	 * Slightly modified version of code from wp-admin/admin.php.
245
	 *
246
	 * @param  string $page_hook
247
	 * @return string
248
	 */
249
	protected function getAdminHook( $page_hook ) {
250
		global $pagenow, $plugin_page;
251
252
		$hook_suffix = '';
253
		if ( ! empty( $page_hook ) ) {
254
			$hook_suffix = $page_hook;
255
		} else if ( isset( $plugin_page ) ) {
256
			$hook_suffix = $plugin_page;
257
		} else if ( isset( $pagenow ) ) {
258
			$hook_suffix = $pagenow;
259
		}
260
261
		return $hook_suffix;
262
	}
263
264
	/**
265
	 * Register admin action to hook into current one.
266
	 *
267
	 * @return void
268
	 */
269
	public function registerAdminAction() {
270
		global $pagenow;
271
272
		if ( $pagenow !== 'admin.php' ) {
273
			return;
274
		}
275
276
		$page_hook = $this->getAdminPageHook();
277
		$hook_suffix = $this->getAdminHook( $page_hook );
278
279
		add_action( "load-{$hook_suffix}", [$this, 'actionAdminLoad'] );
280
		add_action( $hook_suffix, [$this, 'actionAdmin'] );
281
	}
282
283
	/**
284
	 * Act on admin action load.
285
	 *
286
	 * @return void
287
	 */
288
	public function actionAdminLoad() {
289
		$response = $this->handle( $this->request, [''] );
290
291
		if ( ! $response instanceof ResponseInterface ) {
292
			return;
293
		}
294
295
		if ( ! headers_sent() ) {
296
			Response::sendHeaders( $response );
297
		}
298
	}
299
300
	/**
301
	 * Act on admin action.
302
	 *
303
	 * @return void
304
	 */
305
	public function actionAdmin() {
306
		$response = $this->app->resolve( WPEMERGE_RESPONSE_KEY );
307
308
		if ( $response === null ) {
309
			return;
310
		}
311
312
		Response::sendBody( $response );
313
	}
314
}
315