DslAssignment.class.php (1853B)
1 <?php 2 3 namespace dsl\ast; 4 5 use dsl\DslParserException; 6 use dsl\DslRuntimeException; 7 use dsl\DslToken; 8 9 class DslAssignment implements DslStatement 10 { 11 private $target = []; 12 private $value; 13 14 /** 15 * DslAssignment constructor. 16 * @param $target DslStatement 17 * @param $value DslStatement 18 * @throws DslParserException 19 */ 20 public function __construct( $target, $value ) 21 { 22 //echo "<h5>Assignment:</h5><pre>"; var_export( $target ); var_export($value); echo "</pre>"; 23 24 $this->target = $target; 25 $this->value = $value; 26 } 27 28 /** 29 * @param array $context 30 * @return mixed|void 31 * @throws DslRuntimeException 32 */ 33 public function execute( & $context ) { 34 35 $value = $this->value->execute( $context ); 36 37 // if the variable is not already bound in this context it will be created. 38 // there is no need for a "var" or "let". they are completely obsolet. 39 //if ( ! array_key_exists( $this->target->name,$context ) ) 40 // throw new DslRuntimeException('variable \''.$this->target->name.'\' does not exist'); 41 42 $context[ $this->target->name ] = $value; 43 44 return $value; 45 } 46 47 public function parse($tokens) 48 { 49 //echo "<h2>Assignment-Parser</h2><pre>"; var_dump( $tokens ); echo "</pre>"; 50 $this->target = new DslExpression(); 51 $this->value = new DslExpression(); 52 53 $assignmentOperatorFound = false; 54 $targetToken = []; 55 $valueToken = []; 56 57 foreach( $tokens as $token ) { 58 59 if ( $token->type == DslToken::T_OPERATOR && in_array($token->value,['=','+='.'-=']) ) { 60 $assignmentOperatorFound = true; 61 continue; 62 } 63 64 if ( ! $assignmentOperatorFound ) 65 $targetToken[] = $token; 66 else 67 $valueToken[] = $token; 68 } 69 70 if ( $assignmentOperatorFound ) { 71 $this->target->parse( $targetToken ); 72 $this->value ->parse( $valueToken ); 73 } else { 74 $this->value->parse( $targetToken ); 75 $this->target = null; 76 } 77 } 78 }