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

namespace Kufer\Web\Classes\Scripting3;

class ExprBody extends Expr
{
  
  public $body;

  public function __construct(array $body)
  {
    parent::__construct();

    $this->body = $body;
  }

  public function toPHP(bool $isleaf, ParserHelper $phpcode, array $fnvars): string
  {
    $result = '';

    $resultary = \FunctionOperations::filter(function($str) {
      return !empty($str) && $str != '\'\'';
    })(\FunctionOperations::map(static::createFunctionToPHP($isleaf, $phpcode, $fnvars))($this->body));


    if ($isleaf) {
      $result .= \implode('', $resultary);
    } else {
      if (empty($resultary)) {
        $result .= '\'\'';
      } else {
        $result .= \implode('.', $resultary);
      }
    }


    return $result;
  }

  public function toString(): string
  {
    return (new \Kufer\Web\Classes\Stream\ArrayStream($this->body))
      ->map(static function(Expr $e) {
        return $e->toString();
      })
      ->reduce(\FunctionOperations::concat(), '');
  }

  public function optimize(): Expr
  {
    $cntBody = count($this->body);
    if ($cntBody === 0) {
      return new ExprText('');
    } elseif ($cntBody === 1) {
      return $this->body[0];
    } else {
      return $this;
    }
  }
}