Passed
Push — master ( 50ee3e...c1f03e )
by Atanas
02:03
created

ControllerMiddleware::except()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
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\Middleware;
11
12
use WPEmerge;
13
14
/**
15
 * Redirect users who do not have a capability to a specific URL.
16
 */
17
class ControllerMiddleware {
18
	/**
19
	 * Middleware.
20
	 *
21
	 * @var array<string>
22
	 */
23
	protected $middleware = [];
24
25
	/**
26
	 * Methods the middleware applies to.
27
	 *
28
	 * @var array<string>
29
	 */
30
	protected $whitelist = [];
31
32
	/**
33
	 * Methods the middleware does not apply to.
34
	 *
35
	 * @var array<string>
36
	 */
37
	protected $blacklist = [];
38
39
	/**
40
	 * Constructor.
41
	 *
42
	 * @param  string|array<string> $middleware
43
	 */
44
	public function __construct( $middleware ) {
45
		$this->middleware = (array) $middleware;
46
	}
47
48
	/**
49
	 * Get middleware.
50
	 *
51
	 * @codeCoverageIgnore
52
	 * @return array<string>
53
	 */
54
	public function get() {
55
		return $this->middleware;
56
	}
57
58
	/**
59
	 * Set methods the middleware should apply to.
60
	 *
61
	 * @codeCoverageIgnore
62
	 * @param  string|array<string> $methods
63
	 * @return static
64
	 */
65
	public function only( $methods ) {
66
		$this->whitelist = (array) $methods;
67
68
		return $this;
69
	}
70
71
	/**
72
	 * Set methods the middleware should not apply to.
73
	 *
74
	 * @codeCoverageIgnore
75
	 * @param  string|array<string> $methods
76
	 * @return static
77
	 */
78
	public function except( $methods ) {
79
		$this->blacklist = (array) $methods;
80
81
		return $this;
82
	}
83
84
	/**
85
	 * Get whether the middleware applies to the specified method.
86
	 *
87
	 * @param  string $method
88
	 * @return boolean
89
	 */
90
	public function appliesTo( $method ) {
91
		if ( in_array( $method, $this->blacklist, true ) ) {
92
			return false;
93
		}
94
95
		if ( empty( $this->whitelist ) ) {
96
			return true;
97
		}
98
99
		return in_array( $method, $this->whitelist, true );
100
	}
101
}
102