CsrfMiddleware::handle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 6
c 1
b 0
f 1
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 10
cc 3
nc 3
nop 3
crap 12
1
<?php
2
/**
3
 * @package   WPEmerge
4
 * @author    Atanas Angelov <[email protected]>
5
 * @copyright 2017-2019 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\Csrf;
11
12
use Closure;
13
use Psr\Http\Message\ResponseInterface;
14
use WPEmerge\Requests\RequestInterface;
15
16
/**
17
 * Store current request data and clear old request data
18
 */
19
class CsrfMiddleware {
20
	/**
21
	 * CSRF service.
22
	 *
23
	 * @var Csrf
24
	 */
25
	protected $csrf = null;
26
27
	/**
28
	 * Constructor.
29
	 *
30
	 * @param Csrf $csrf
31
	 */
32
	public function __construct( $csrf ) {
33
		$this->csrf = $csrf;
34
	}
35
36
	/**
37
	 * Reject requests that fail nonce validation.
38
	 *
39
	 * @param  RequestInterface     $request
40
	 * @param  Closure              $next
41
	 * @param  mixed                $action
42
	 * @return ResponseInterface
43
	 * @throws InvalidCsrfTokenException
44
	 */
45
	public function handle( RequestInterface $request, Closure $next, $action = -1 ) {
46
		if ( ! $request->isReadVerb() ) {
47
			$token = $this->csrf->getTokenFromRequest( $request );
48
			if ( ! $this->csrf->isValidToken( $token, $action ) ) {
49
				throw new InvalidCsrfTokenException();
50
			}
51
		}
52
53
		$this->csrf->generateToken( $action );
54
55
		return $next( $request );
56
	}
57
}
58