1 | <?php |
||
2 | /** |
||
3 | * Act as whitelist (or blacklist). |
||
4 | * |
||
5 | */ |
||
6 | class CWhitelist |
||
7 | { |
||
8 | /** |
||
9 | * Array to contain the whitelist options. |
||
10 | */ |
||
11 | private $whitelist = array(); |
||
12 | |||
13 | |||
14 | |||
15 | /** |
||
16 | * Set the whitelist from an array of strings, each item in the |
||
17 | * whitelist should be a regexp without the surrounding / or #. |
||
18 | * |
||
19 | * @param array $whitelist with all valid options, |
||
20 | * default is to clear the whitelist. |
||
21 | * |
||
22 | * @return $this |
||
23 | */ |
||
24 | 6 | public function set($whitelist = array()) |
|
25 | { |
||
26 | 6 | if (!is_array($whitelist)) { |
|
27 | 1 | throw new Exception("Whitelist is not of a supported format."); |
|
28 | } |
||
29 | |||
30 | 5 | $this->whitelist = $whitelist; |
|
31 | 5 | return $this; |
|
32 | } |
||
33 | |||
34 | |||
35 | |||
36 | /** |
||
37 | * Check if item exists in the whitelist. |
||
38 | * |
||
39 | * @param string $item string to check. |
||
40 | * @param array $whitelist optional with all valid options, default is null. |
||
41 | * |
||
42 | * @return boolean true if item is in whitelist, else false. |
||
43 | */ |
||
44 | 5 | public function check($item, $whitelist = null) |
|
45 | { |
||
46 | 5 | if ($whitelist !== null) { |
|
47 | 2 | $this->set($whitelist); |
|
48 | 2 | } |
|
49 | |||
50 | 5 | if (empty($item) or empty($this->whitelist)) { |
|
51 | 1 | return false; |
|
52 | } |
||
53 | |||
54 | 4 | foreach ($this->whitelist as $regexp) { |
|
55 | 4 | if (preg_match("#$regexp#", $item)) { |
|
56 | 2 | return true; |
|
57 | } |
||
58 | 2 | } |
|
59 | |||
60 | 2 | return false; |
|
61 | } |
||
62 | } |
||
63 |