<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Scripting3;

class ExprVar extends Expr
{
  
  public $varname;

  
  public $isInBody;

  
  public $isInCondition;

  
  public $filter;

  
  public function __construct($varname, $isInBody = true, bool $isInCondition = false, ?array $filter = null)
  {
    parent::__construct();

    $this->varname = $varname;
    $this->isInBody = $isInBody;
    $this->isInCondition = $isInCondition;
    $this->filter = $filter;
  }

  private function toInnerString(): string
  {
    $result = '';
    if (is_array($this->varname)) {
      $result .= (new \Kufer\Web\Classes\Stream\ArrayStream($this->varname))
        ->map(static function($e) {
          return \is_string($e) ? $e : $e->toString();
        })
        ->implode(':');
    } elseif (\is_string($this->varname)) {
      $result .= $this->varname;
    } else {
      $result .= $this->varname->toString();
    }

    return $result;
  }

  public function toString(): string
  {
    $result = $this->toInnerString();

    return '{%' . $result . '%}';
  }

  public function toPHP(bool $isleaf, ParserHelper $phpcode, array $fnvars): string
  {
    $result = $phpcode->createVariable($this->varname, $fnvars, $this->isInBody, $this->filter);

    $addUsedVariable = '$varstore->addUsedVariable(\'' . strtr($this->toInnerString(), array(
      '\\' => '\\\\',
      '\'' => '\\\''
    )) . '\', ' . ($this->isInCondition ? 'true' : 'false') . ')';

    if ($isleaf) {
      $result = '$result.=' . $result . ";\n" . $addUsedVariable . ";\n";
    } else {
      $result .= ' . (' . $addUsedVariable . ' ?? \'\')';
    }

    return $result;
  }
}