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\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 string[] |
22
|
|
|
*/ |
23
|
|
|
protected $middleware = []; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Methods the middleware applies to. |
27
|
|
|
* |
28
|
|
|
* @var string[] |
29
|
|
|
*/ |
30
|
|
|
protected $whitelist = []; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Methods the middleware does not apply to. |
34
|
|
|
* |
35
|
|
|
* @var string[] |
36
|
|
|
*/ |
37
|
|
|
protected $blacklist = []; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Constructor. |
41
|
|
|
* |
42
|
|
|
* @codeCoverageIgnore |
43
|
|
|
* @param string|string[] $middleware |
44
|
|
|
*/ |
45
|
|
|
public function __construct( $middleware ) { |
46
|
|
|
$this->middleware = (array) $middleware; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Get middleware. |
51
|
|
|
* |
52
|
|
|
* @codeCoverageIgnore |
53
|
|
|
* @return string[] |
54
|
|
|
*/ |
55
|
|
|
public function get() { |
56
|
|
|
return $this->middleware; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Set methods the middleware should apply to. |
61
|
|
|
* |
62
|
|
|
* @codeCoverageIgnore |
63
|
|
|
* @param string|string[] $methods |
64
|
|
|
* @return static |
65
|
|
|
*/ |
66
|
|
|
public function only( $methods ) { |
67
|
|
|
$this->whitelist = (array) $methods; |
68
|
|
|
|
69
|
|
|
return $this; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Set methods the middleware should not apply to. |
74
|
|
|
* |
75
|
|
|
* @codeCoverageIgnore |
76
|
|
|
* @param string|string[] $methods |
77
|
|
|
* @return static |
78
|
|
|
*/ |
79
|
|
|
public function except( $methods ) { |
80
|
|
|
$this->blacklist = (array) $methods; |
81
|
|
|
|
82
|
|
|
return $this; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* Get whether the middleware applies to the specified method. |
87
|
|
|
* |
88
|
|
|
* @param string $method |
89
|
|
|
* @return boolean |
90
|
|
|
*/ |
91
|
4 |
|
public function appliesTo( $method ) { |
92
|
4 |
|
if ( in_array( $method, $this->blacklist, true ) ) { |
93
|
2 |
|
return false; |
94
|
|
|
} |
95
|
|
|
|
96
|
4 |
|
if ( empty( $this->whitelist ) ) { |
97
|
2 |
|
return true; |
98
|
|
|
} |
99
|
|
|
|
100
|
2 |
|
return in_array( $method, $this->whitelist, true ); |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|