XmlImportTemplateCodeGenerator.php 11.4 KB
Newer Older
imac's avatar
imac committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
<?php
/**
 * @author Olexandr Zanichkovsky <olexandr.zanichkovsky@zophiatech.com>
 * @package General
 */

require_once dirname(__FILE__) . '/XmlImportConfig.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstSequence.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstText.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstPrint.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstInteger.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstFloat.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstString.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstXPath.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstFunction.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstWith.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstForeach.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstIf.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstMath.php';
require_once dirname(__FILE__) . '/ast/XmlImportAstSpintax.php';

/**
 * Is used to generate a PHP code from AST (Abstract Syntax Tree)
 */
class XmlImportTemplateCodeGenerator
{

  /**
   * Top level statement sequence
   *
   * @var XmlImportAstSequence
   */
  private $sequence;

  /**
   * statement sequence stack
   *
   * @var array
   */
  private $sequenceStack = array();

  /**
   * SimpleXmlElement variable number
   *
   * @var int
   */
  private $xmlVariableNumber = 0;

  /**
   * Previous statement
   *
   * @var XmlImportAstStatement
   */
  private $previousStatement = null;

  /**
   * Stack of SimpleXmlElement instances
   *
   * @var array
   */
  private $xmlStack = array();

  /**
   * Whether PHP tag is open
   *
   * @var bool
   */
  private $isPhpTagOpen = false;

  /**
   * Creates new instance
   *
   * @param XmlImportAstSequence $sequence
   */
  public function __construct(XmlImportAstSequence $sequence)
  {
    $this->sequence = $sequence;
  }

  /**
   * Generates the code and returns the filename under which it was stored in
   * cache directory. If $filename is null then it is generated automatically
   *
   * @param string $filename
   * @return string
   */
  public function generate($filename = null)
  {
  	$result = '';
    if (count($this->sequence->getVariables()))
    {
      $var = '$x' . $this->xmlVariableNumber++;
      array_push($this->xmlStack, $var);
      $result .= $this->openPhpTag() . $var . ' = $this->xml;' ;
    }    
    $result .= $this->generateForSequence($this->sequence);

    if (count($this->sequence->getVariables()))
    {      
      array_pop($this->xmlStack);
    }	
    if (is_null($filename))
    {
       $filename = @tempnam(XmlImportConfig::getInstance()->getCacheDirectory(), 'xim');
    }
	  if ( ! $filename or ! @is_writable($filename) ){
      $uploads  = wp_upload_dir();
      $targetDir = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
      $filename = $targetDir . DIRECTORY_SEPARATOR . wp_unique_filename($targetDir, 'tmpfile');
    }
    
    file_put_contents($filename, $result);
    //@chmod($filename, 0666);
    return $filename;
  }

  /**
   * Generates code for a statement sequence
   *
   * @param XmlImportAstSequence $sequence
   * @return string
   */
  private function generateForSequence(XmlImportAstSequence $sequence)
  {
    array_push($this->sequenceStack, $sequence);
    $result = '';

    if (count($sequence->getVariableDefinitions()) > 0)
    {
      $result .= $this->openPhpTag();
      foreach ($sequence->getVariableDefinitions() as $xpath)
      {        
        $result .= PHP_EOL . str_replace('{{XML}}', $this->xmlStack[count($this->xmlStack) - 1], $xpath);
      }
      $result .= PHP_EOL;
    }
    foreach ($sequence->getStatements() as $statement)
    {            
      $result .= $this->generateForStatement($statement);
    }
    array_pop($this->sequenceStack);

    return $result;
  }

  /**
   * Generates code for a statement
   *
   * @param XmlImportAstStatement $statement
   * @return string
   */
  private function generateForStatement(XmlImportAstStatement $statement)
  {
    $result = '';
    if ($statement instanceof XmlImportAstText)
    {
      $result .= $this->closePhpTag();
      $text = preg_replace('%<\?|\?>%', '<?php echo "$0"; ?>', $statement->getValue()); // escape php tags
      if ($this->previousStatement instanceof XmlImportAstPrint && (strpos($text, "\n") === 0 || strpos($text, "\r\n") === 0))
      {
        $result .= PHP_EOL;
      }
      $result .= $text;
    }
    else
    {
      $result .= $this->openPhpTag();
      if ($statement instanceof XmlImportAstPrint)
      {		
        $result .= 'echo ';
        $result .= $this->generateForExpression($statement->getValue(), true) . ';';
      }
      elseif ($statement instanceof XmlImportAstWith)
      {
        $var = '$x' . $this->xmlVariableNumber++;
        $result .= PHP_EOL . $var . ' = ' ;
        $result .= $this->generateForExpression($statement->getXpath()) . ';' . PHP_EOL;

        array_push($this->xmlStack, $var);
        $result .= 'if (' . $var . ' !== false && count(' . $var . ') > 0) :' . PHP_EOL . $var .
          ' = ' . $var . '[0];' . PHP_EOL;
        $result .= $this->generateForSequence($statement->getBody());
        array_pop($this->xmlStack);
        $result .= $this->openPhpTag() . PHP_EOL . 'endif;' . PHP_EOL;
      }
      elseif ($statement instanceof XmlImportAstForeach)
      {
        $var = '$x' . $this->xmlVariableNumber++;                    
        $result .= PHP_EOL . 'foreach (' . $this->generateForExpression($statement->getXPath(), false) .
          ' as ' . $var . ') :' . PHP_EOL;       
        array_push($this->xmlStack, $var);
        $result .= $this->generateForSequence($statement->getBody());
        $result .= $this->openPhpTag() . PHP_EOL . 'endforeach;' . PHP_EOL;        
        array_pop($this->xmlStack);
      }
      elseif ($statement instanceof XmlImportAstIf)
      {                
        $result .= PHP_EOL . 'if (' . $this->generateForExpression($statement->getCondition()) .  ') :' . PHP_EOL;
        $result .= $this->generateForSequence($statement->getIfBody());

        foreach ($statement->getElseIfs() as $elseif)
        {
          $result .= $this->openPhpTag() . PHP_EOL . 'elseif (' . $this->generateForExpression($elseif->getCondition()) . ') :' . PHP_EOL;
          $result .= $this->generateForSequence($elseif->getBody());
        }
        if (!is_null($body = $statement->getElseBody()))
        {          
          $result .= $this->openPhpTag() . PHP_EOL . 'else :' . PHP_EOL;
          $result .= $this->generateForSequence($body);
        }
        $result .= $this->openPhpTag() . PHP_EOL . 'endif;' . PHP_EOL;        
      }
	  
    }
    $this->previousStatement = $statement;
    return $result;
  }

  /**
   * Generates code for expression
   *
   * @param XmlImportAstExpression $expression
   * @param bool $inPrint whether in print or in clause or function argument
   * @return string
   */
  private function generateForExpression(XmlImportAstExpression $expression, $inPrint = false)
  {
	
    switch (get_class($expression))
    {
      case 'XmlImportAstString':        
        $result = '"' . $this->getEscapedValue($expression->getValue()) . '"';
        break;

      case 'XmlImportAstInteger':
      case 'XmlImportAstFloat':
        $result = $expression->getValue();
        break;

      case 'XmlImportAstXPath':              
        if ($inPrint)
        {          
          $variables = $this->sequenceStack[count($this->sequenceStack) - 1]->getVariables();          
          $result = '$this->getValue(' . $variables[$expression->getValue()] . ')';                    
        }
        else
        {          
          $variables = $this->sequenceStack[count($this->sequenceStack) - 1]->getVariables();          
          $result = $variables[$expression->getValue()];                              
        }
        break;

      case 'XmlImportAstFunction':      
        $result = $this->generateForFunction($expression);
		    break;
  	  
      case 'XmlImportAstMath':
          $result = $this->generateForMath($expression);
        break;

      case 'XmlImportAstSpintax':
          $result = $this->generateForSpintax($expression);
        break;
    }
    return $result;
  }

  /**
   * Generates code for a function
   *
   * @param XmlImportAstFunction $function
   * @return string
   */
  private function generateForFunction(XmlImportAstFunction $function)
  {    
    $result = $function->getName() . '(';
    $arguments = $function->getArguments();
    
    for($i = 0; $i < count($arguments); $i++)
    {		      
      $result .= $this->generateForExpression($arguments[$i], true);
      if ($i < (count($arguments) - 1))
        $result .= ', ';
    }
    $result .= ')';
	
    return $result;
  }
  
  /**
   * Generates code for a function
   *
   * @param XmlImportAstFunction $function
   * @return string
   */
  private function generateForMath(XmlImportAstMath $math)
  {
    $result = '';
    $arguments = $math->getArguments();
    for($i = 0; $i < count($arguments); $i++)
    {		
      $result .= $this->generateForExpression($arguments[$i], true);      	  
    }
    
    return 'number_format('.str_replace("\"", "", $result).',2)';
  }

  /**
   * Generates code for a function
   *
   * @param XmlImportAstSpintax $expression
   * @return string
   */
  private function generateForSpintax(XmlImportAstSpintax $spintax)
  {
    $result    = '';
    $arguments = $spintax->getArguments();
    $elements  = array();
    $buf       = array();

    for($i = 0; $i < count($arguments); $i++)
    {         

      if ($arguments[$i]->getValue() != '|') array_push($buf, $this->generateForExpression($arguments[$i], true)); else { array_push($elements, $buf); $buf = array();}
      
    }        

    array_push($elements, $buf);

    if (!empty($elements) and is_array($elements)){
      
      $spintax_arr = $this->generateVariation($elements);

      foreach ($spintax_arr as $key => $value) {
        $result .= "\"<p>\".".implode(".", $value).".\"</p>\""; if ($key != count($spintax_arr) - 1) $result .= ".";
      }

    }
    
    return $result;
  }

  function generateVariation($A, $i = 0)
  {
      $result = array();

      if ($i < count($A))
      {
          $variations = $this->generateVariation($A, $i + 1);

          for ($j = 0; $j < count($A[$i]); $j++)
          {
              if ($variations)
              {
                  foreach ($variations as $variation)
                  {
                      $result[] = array_merge(array($A[$i][$j]), $variation);
                  }
              }
              else
              {
                  $result[] = array($A[$i][$j]);
              }
          }
      }

      return $result;
  }
  /**
   * Add PHP open tag if needed
   *
   * @return string
   */
  private function openPhpTag()
  {
    $result = '';
    if (!$this->isPhpTagOpen)
    {
      $this->isPhpTagOpen = true;
      $result = '<?php ';
    }
    return $result;
  }

  /**
   * Adds PHP close tag if needed
   *
   * @return string
   */
  private function closePhpTag()
  {
    $result = '';
    if ($this->isPhpTagOpen)
    {
      $this->isPhpTagOpen = false;
      $result = '?>';
    }
    return $result;
  }

  /**
   * Gets escaped value
   *
   * @return string
   */
  private function getEscapedValue($value)
  {
    $escapedValue = strtr($value, array(
    	"\n" => "\\n",
    	"\t" => "\\t",
    	"\r" => "\\r",
    	"$" => "\\$",
    	"\"" => "\\\"",
    	"\\" => "\\\\",
    ));
    return $escapedValue;
  }
}