| 1 |
<?php // phpcs:ignore |
| 2 |
/** |
| 3 |
* Array-backed expression engine. |
| 4 |
* |
| 5 |
* @package PRAD |
| 6 |
* @since 1.5.8 |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace PRAD\Includes\Common\Formula; |
| 10 |
|
| 11 |
defined( 'ABSPATH' ) || exit; |
| 12 |
|
| 13 |
/** |
| 14 |
* Resolves [placeholders] from an associative array. |
| 15 |
*/ |
| 16 |
class Array_Expression_Engine extends Abstract_Expression_Engine { |
| 17 |
|
| 18 |
/** |
| 19 |
* Evaluates an expression using provided dynamics. |
| 20 |
* |
| 21 |
* @param string $expression Expression to evaluate. |
| 22 |
* @param array $dynamics Map of placeholder name => value. |
| 23 |
* |
| 24 |
* @return mixed |
| 25 |
* @throws Expression_Exception If the expression cannot be parsed or evaluated. |
| 26 |
*/ |
| 27 |
public static function evaluate_expression( $expression, array $dynamics = array() ) { |
| 28 |
$engine = new self(); |
| 29 |
return $engine->evaluate( $expression, $dynamics ); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* Evaluate an expression, returning 0 when the expression is invalid. |
| 34 |
* |
| 35 |
* Useful when you prefer a soft-fail behavior instead of surfacing parser errors. |
| 36 |
* |
| 37 |
* @param string $expression Expression to evaluate. |
| 38 |
* @param array $dynamics Map of placeholder name => value. |
| 39 |
* |
| 40 |
* @return mixed |
| 41 |
*/ |
| 42 |
public static function evaluate_expression_safe( $expression, array $dynamics = array() ) { |
| 43 |
try { |
| 44 |
return self::evaluate_expression( $expression, $dynamics ); |
| 45 |
} catch ( Expression_Exception $e ) { |
| 46 |
return 0; |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Retrieves the dynamic value for a given placeholder name from the context array. |
| 52 |
* |
| 53 |
* @param string $name The placeholder name to resolve. |
| 54 |
* @param array $context Associative array of placeholder values. |
| 55 |
* |
| 56 |
* @return mixed |
| 57 |
*/ |
| 58 |
public function get_dynamic_value( $name, array $context = array() ) { |
| 59 |
if ( array_key_exists( $name, $context ) ) { |
| 60 |
return $context[ $name ]; |
| 61 |
} |
| 62 |
// By convention, missing variables are 0. |
| 63 |
return 0; |
| 64 |
} |
| 65 |
} |
| 66 |
|