WC_Eval_Math::evaluate( string $expr )

Evaluate maths string.


Description Description


Parameters Parameters

$expr

(Required)


Top ↑

Return Return

(mixed)


Top ↑

Source Source

File: includes/libraries/class-wc-eval-math.php

		public static function evaluate( $expr ) {
			self::$last_error = null;
			$expr = trim( $expr );
			if ( substr( $expr, -1, 1 ) == ';' ) {
				$expr = substr( $expr, 0, strlen( $expr ) -1 ); // strip semicolons at the end
			}
			// ===============
			// is it a variable assignment?
			if ( preg_match( '/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches ) ) {
				if ( in_array( $matches[1], self::$vb ) ) { // make sure we're not assigning to a constant
					return self::trigger( "cannot assign to constant '$matches[1]'" );
				}
				if ( ( $tmp = self::pfx( self::nfx( $matches[2] ) ) ) === false ) {
					return false; // get the result and make sure it's good
				}
				self::$v[ $matches[1] ] = $tmp; // if so, stick it in the variable array
				return self::$v[ $matches[1] ]; // and return the resulting value
				// ===============
				// is it a function assignment?
			} elseif ( preg_match( '/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches ) ) {
				$fnn = $matches[1]; // get the function name
				if ( in_array( $matches[1], self::$fb ) ) { // make sure it isn't built in
					return self::trigger( "cannot redefine built-in function '$matches[1]()'" );
				}
				$args = explode( ",", preg_replace( "/\s+/", "", $matches[2] ) ); // get the arguments
				if ( ( $stack = self::nfx( $matches[3] ) ) === false ) {
					return false; // see if it can be converted to postfix
				}
				$stack_size = count( $stack );
				for ( $i = 0; $i < $stack_size; $i++ ) { // freeze the state of the non-argument variables
					$token = $stack[ $i ];
					if ( preg_match( '/^[a-z]\w*$/', $token ) and ! in_array( $token, $args ) ) {
						if ( array_key_exists( $token, self::$v ) ) {
							$stack[ $i ] = self::$v[ $token ];
						} else {
							return self::trigger( "undefined variable '$token' in function definition" );
						}
					}
				}
				self::$f[ $fnn ] = array( 'args' => $args, 'func' => $stack );
				return true;
				// ===============
			} else {
				return self::pfx( self::nfx( $expr ) ); // straight up evaluation, woo
			}
		}


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.