| 1 |
<?php |
| 2 |
/** |
| 3 |
* Rule engine handler. |
| 4 |
* |
| 5 |
* @package ContentControl\RuleEngine |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace ContentControl\RuleEngine; |
| 9 |
|
| 10 |
use ContentControl\Models\RuleEngine\Set; |
| 11 |
|
| 12 |
/** |
| 13 |
* Handler for rule engine. |
| 14 |
* |
| 15 |
* @package ContentControl\RuleEngine |
| 16 |
*/ |
| 17 |
class Handler { |
| 18 |
|
| 19 |
/** |
| 20 |
* All sets for this handler. |
| 21 |
* |
| 22 |
* @var Set[] |
| 23 |
*/ |
| 24 |
public $sets; |
| 25 |
|
| 26 |
/** |
| 27 |
* Whether check requires `any`|`all`|`none` sets to pass. |
| 28 |
* |
| 29 |
* @var string |
| 30 |
*/ |
| 31 |
public $any_all_none; |
| 32 |
|
| 33 |
/** |
| 34 |
* Build a list of sets. |
| 35 |
* |
| 36 |
* @param array{id:string,label:string,query:array<mixed>}[] $sets Set data. |
| 37 |
* @param string $any_all_none Whether require `any`|`all`|`none` sets to pass checks. |
| 38 |
*/ |
| 39 |
public function __construct( $sets, $any_all_none = 'all' ) { |
| 40 |
$this->any_all_none = $any_all_none; |
| 41 |
$this->sets = []; |
| 42 |
|
| 43 |
foreach ( $sets as $set ) { |
| 44 |
$this->sets[] = new Set( $set ); |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Check if this set has JS based rules. |
| 50 |
* |
| 51 |
* @return bool |
| 52 |
*/ |
| 53 |
public function has_js_rules() { |
| 54 |
foreach ( $this->sets as $set ) { |
| 55 |
if ( $set->has_js_rules() ) { |
| 56 |
return true; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
return false; |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Checks the rules of all sets using the any/all comparitor. |
| 65 |
* |
| 66 |
* @return boolean |
| 67 |
*/ |
| 68 |
public function check_rules() { |
| 69 |
$checks = []; |
| 70 |
|
| 71 |
foreach ( $this->sets as $set ) { |
| 72 |
$check = $set->check_rules(); |
| 73 |
// We try to bail early, but just in case we'll add it to the array. |
| 74 |
$checks[] = $check; |
| 75 |
|
| 76 |
// Bail early if we're checking for all and found one that failed. |
| 77 |
if ( 'all' === $this->any_all_none && false === $check ) { |
| 78 |
return false; |
| 79 |
} |
| 80 |
|
| 81 |
// Bail early if we're checking for any and found one. |
| 82 |
if ( 'any' === $this->any_all_none && true === $check ) { |
| 83 |
return true; |
| 84 |
} |
| 85 |
|
| 86 |
// Bail early if we're checking for none and found one. |
| 87 |
if ( 'none' === $this->any_all_none && true === $check ) { |
| 88 |
return false; |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
switch ( $this->any_all_none ) { |
| 93 |
case 'any': |
| 94 |
return in_array( true, $checks, true ); |
| 95 |
case 'all': |
| 96 |
default: |
| 97 |
return ! in_array( false, $checks, true ); |
| 98 |
case 'none': |
| 99 |
return ! in_array( true, $checks, true ); |
| 100 |
} |
| 101 |
} |
| 102 |
} |
| 103 |
|