| 1 |
<?php |
| 2 |
|
| 3 |
defined('ABSPATH') || exit; |
| 4 |
|
| 5 |
|
| 6 |
class Blockspare_TB_Condition_Registry |
| 7 |
{ |
| 8 |
|
| 9 |
/** |
| 10 |
* Registered conditions, keyed by slug. |
| 11 |
* |
| 12 |
* @var Blockspare_TB_Condition_Interface[] |
| 13 |
*/ |
| 14 |
private $conditions = array(); |
| 15 |
|
| 16 |
/** |
| 17 |
* Registers a condition instance. |
| 18 |
* |
| 19 |
* @param Blockspare_TB_Condition_Interface $condition Condition to add. |
| 20 |
*/ |
| 21 |
public function register(Blockspare_TB_Condition_Interface $condition) |
| 22 |
{ |
| 23 |
$this->conditions[$condition->get_slug()] = $condition; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Registers the conditions this plugin ships with out of the box. |
| 28 |
*/ |
| 29 |
public function register_core_conditions() |
| 30 |
{ |
| 31 |
$core = array( |
| 32 |
new Blockspare_TB_Condition_Entire_Site(), |
| 33 |
new Blockspare_TB_Condition_Front_Page(), |
| 34 |
new Blockspare_TB_Condition_Single(), |
| 35 |
new Blockspare_TB_Condition_Archive(), |
| 36 |
new Blockspare_TB_Condition_Category(), |
| 37 |
new Blockspare_TB_Condition_Author(), |
| 38 |
new Blockspare_TB_Condition_Tag(), |
| 39 |
new Blockspare_TB_Condition_Date_Archive(), |
| 40 |
new Blockspare_TB_Condition_Search(), |
| 41 |
new Blockspare_TB_Condition_404(), |
| 42 |
); |
| 43 |
|
| 44 |
foreach ($core as $condition) { |
| 45 |
$this->register($condition); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Returns all registered conditions. |
| 51 |
* |
| 52 |
* @return Blockspare_TB_Condition_Interface[] |
| 53 |
*/ |
| 54 |
public function all() |
| 55 |
{ |
| 56 |
return $this->conditions; |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
public function matches($ruleset) |
| 61 |
{ |
| 62 |
foreach (isset($ruleset['exclude']) ? $ruleset['exclude'] : array() as $rule) { |
| 63 |
if ($this->rule_matches($rule)) { |
| 64 |
return false; |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
foreach (isset($ruleset['include']) ? $ruleset['include'] : array() as $rule) { |
| 69 |
if ($this->rule_matches($rule)) { |
| 70 |
return true; |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
return false; |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Evaluates a single rule (['type' => ..., 'settings' => ...]). |
| 79 |
* |
| 80 |
* @param array $rule Single rule. |
| 81 |
* @return bool |
| 82 |
*/ |
| 83 |
private function rule_matches($rule) |
| 84 |
{ |
| 85 |
$type = isset($rule['type']) ? $rule['type'] : ''; |
| 86 |
|
| 87 |
if (! isset($this->conditions[$type])) { |
| 88 |
return false; |
| 89 |
} |
| 90 |
|
| 91 |
return $this->conditions[$type]->is_match(isset($rule['settings']) ? $rule['settings'] : array()); |
| 92 |
} |
| 93 |
} |
| 94 |
|