scriptbox

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

DslFunctionCall.class.php (1948B)


      1 <?php
      2 
      3 namespace dsl\ast;
      4 
      5 use dsl\DslRuntimeException;
      6 use dsl\DslToken;
      7 
      8 class DslFunctionCall implements DslStatement
      9 {
     10 	public $name;
     11 	private $parameters;
     12 
     13 	/**
     14 	 * DslFunctionCall constructor.
     15 	 * @param $name
     16 	 * @param $parameters DslToken[][]
     17 	 */
     18 	public function __construct($name, $parameters)
     19 	{
     20 		$this->name       = $name;
     21 		$this->parameters = $parameters;
     22 	}
     23 
     24 
     25 	/**
     26 	 * @throws DslRuntimeException
     27 	 */
     28 	public function execute(& $context ) {
     29 
     30 		$function = $this->name->execute( $context );
     31 
     32 
     33 		//if   ( ! array_key_exists( $name, $context ) )
     34 		//	throw new DslRuntimeException('function \''.$this->name.'\' does not exist.');
     35 
     36 		if   ( $this->parameters == null )
     37 			$parameterValues = []; // parameterless functions.
     38 		else
     39 			$parameterValues = $this->parameters->execute( $context );
     40 
     41 		// if there is only 1 parameter it must be converted to an array.
     42 		// if there are more than 1 parameter, it is already a sequence
     43 		if   ( ! is_array($parameterValues)) $parameterValues = array($parameterValues);
     44 
     45 
     46 		if   ( $function instanceof DslFunction ) {
     47 
     48 			$parameters = $function->parameters;
     49 
     50 			if   ( sizeof($parameters) > sizeof($parameterValues) )
     51 				throw new DslRuntimeException('function call has '.sizeof($parameterValues).' parameters but the function has '.sizeof($parameters).' parameters');
     52 
     53 			// Put all function parameters to the function context.
     54 			$parameterContext = array_combine( $parameters, array_slice($parameterValues,0,sizeof($parameters)) );
     55 			$subContext = array_merge( $context,$parameterContext );
     56 
     57 			return $function->execute( $subContext );
     58 
     59 		}
     60 		elseif   ( is_callable($function) ) {
     61 
     62 			//var_export( call_user_func_array( $function, $parameterValues) );
     63 			return call_user_func_array( $function, $parameterValues);
     64 		}
     65 		else
     66 			throw new DslRuntimeException('function is not callable'.var_export($function));
     67 	}
     68 
     69 	public function parse($tokens)
     70 	{
     71 		$this->statements[] = $tokens;
     72 	}
     73 }