CodeWriter.php 12.7 KB
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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
<?php
/**
 * PHPTAL templating engine
 *
 * PHP Version 5
 *
 * @category HTML
 * @package  PHPTAL
 * @author   Laurent Bedubourg <lbedubourg@motion-twin.com>
 * @author   Kornel Lesiński <kornel@aardvarkmedia.co.uk>
 * @license  http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
 * @version  SVN: $Id: CodeWriter.php 735 2009-09-25 16:54:56Z kornel $
 * @link     http://phptal.org/
 */
/**
 * Helps generate php representation of a template.
 *
 * @package PHPTAL
 * @subpackage Php
 * @author Laurent Bedubourg <lbedubourg@motion-twin.com>
 */
class PHPTAL_Php_CodeWriter
{    
    /**
     * max id of variable to give as temp
     */
    private $temp_var_counter=0;
    /**
     * stack with free'd variables
     */
    private $temp_recycling=array();
    
    /**
     * keeps track of seen functions for function_exists
     */
    private $known_functions = array();

    
    public function __construct(PHPTAL_Php_State $state)
    {
        $this->_state = $state;
    }

    public function createTempVariable()
    {
        if (count($this->temp_recycling)) return array_shift($this->temp_recycling);
        return '$_tmp_'.(++$this->temp_var_counter);
    }

    public function recycleTempVariable($var)
    {
        if (substr($var,0,6)!=='$_tmp_') throw new PHPTAL_Exception("Invalid variable recycled");
        $this->temp_recycling[] = $var;
    }

    public function getCacheFilesBaseName()
    {
        return $this->_state->getCacheFilesBaseName();
    }

    public function getResult()
    {
        $this->flush();
        $this->_result = trim($this->_result);
        return $this->_result;
    }

    /**
     * set full '<!DOCTYPE...>' string to output later
     * 
     * @param string $dt
     * @return void
     */
    public function setDocType($dt)
    {
        $this->_doctype = $dt;
    }

    /**
     * set full '<?xml ?>' string to output later
     * 
     * @param string $dt
     * @return void
     */
    public function setXmlDeclaration($dt)
    {
        $this->_xmldeclaration = $dt;
    }

    /**
     * functions later generated and checked for existence will have this prefix added
     * (poor man's namespace)
     * 
     * @param string $prefix
     * @return void
     */
    public function setFunctionPrefix($prefix)
    {
        $this->_functionPrefix = $prefix;
    }

    /**
     * @return string
     */
    public function getFunctionPrefix()
    {
        return $this->_functionPrefix;
    }

    /**
     * @see PHPTAL_Php_State::setTalesMode()
     * 
     * @param string $mode
     * @return string
     */
    public function setTalesMode($mode)
    {
        return $this->_state->setTalesMode($mode);
    }

    public function splitExpression($src)
    {
        preg_match_all('/(?:[^;]+|;;)+/sm', $src, $array);
        $array = $array[0];
        foreach ($array as &$a) $a = str_replace(';;', ';', $a);
        return $array;
    }

    public function evaluateExpression($src)
    {
        return $this->_state->evaluateExpression($src);
    }

    public function indent()
    {
        $this->_indentation ++;
    }

    public function unindent()
    {
        $this->_indentation --;
    }

    public function flush()
    {
        $this->flushCode();
        $this->flushHtml();
    }

    public function noThrow($bool)
    {
        if ($bool) {
            $this->pushCode('$ctx->noThrow(true)');
        } else {
            $this->pushCode('$ctx->noThrow(false)');
        }
    }

    public function flushCode()
    {
        if (count($this->_codeBuffer) == 0) return;

        // special treatment for one code line
        if (count($this->_codeBuffer) == 1) {
            $codeLine = $this->_codeBuffer[0];
            // avoid adding ; after } and {
            if (!preg_match('/\}\s*$|\{\s*$/', $codeLine))
                $this->_result .= '<?php '.$codeLine."; ?>\n"; // PHP consumes newline
            else
                $this->_result .= '<?php '.$codeLine." ?>\n"; // PHP consumes newline
            $this->_codeBuffer = array();
            return;
        }

        $this->_result .= '<?php '."\n";
        foreach ($this->_codeBuffer as $codeLine) {
            // avoid adding ; after } and {
            if (!preg_match('/\}\s*$|\{\s*$/', $codeLine))
                $this->_result .= $codeLine . ' ;'."\n";
            else
                $this->_result .= $codeLine;
        }
        $this->_result .= "?>\n";// PHP consumes newline
        $this->_codeBuffer = array();
    }

    public function flushHtml()
    {
        if (count($this->_htmlBuffer) == 0) return;

        $this->_result .= implode('', $this->_htmlBuffer);
        $this->_htmlBuffer = array();
    }

    /**
     * Generate code for setting DOCTYPE
     *
     * @param bool $called_from_macro for error checking: unbuffered output doesn't support that
     */
    public function doDoctype($called_from_macro = false)
    {
        if ($this->_doctype) {
            $code = '$ctx->setDocType('.$this->str($this->_doctype).','.($called_from_macro?'true':'false').')';
            $this->pushCode($code);
        }
    }
    
    /**
     * Generate XML declaration 
     *
     * @param bool $called_from_macro for error checking: unbuffered output doesn't support that
     */
    public function doXmlDeclaration($called_from_macro = false)
    {
        if ($this->_xmldeclaration && $this->getOutputMode() !== PHPTAL::HTML5) {
            $code = '$ctx->setXmlDeclaration('.$this->str($this->_xmldeclaration).','.($called_from_macro?'true':'false').')';
            $this->pushCode($code);
        }
    }

    public function functionExists($name)
    {
        return isset($this->known_functions[$this->_functionPrefix . $name]);
    }

    public function doTemplateFile($functionName, PHPTAL_Dom_Element $treeGen)
    {
        $this->doComment("\n*** DO NOT EDIT THIS FILE ***\n\nGenerated by PHPTAL from ".$treeGen->getSourceFile()." (edit that file instead)");
        $this->doFunction($functionName, '$tpl, $ctx');
        $this->setFunctionPrefix($functionName . "_");
        $this->doSetVar('$_thistpl', '$tpl');
        $this->doSetVar('$_translator', '$tpl->getTranslator()');
        $treeGen->generateCode($this);
        $this->doComment("end");
        $this->doEnd('function');        
    }

    public function doFunction($name, $params)
    {
        $name = $this->_functionPrefix . $name;
        $this->known_functions[$name] = true;

        $this->pushCodeWriterContext();
        $this->pushCode("function $name($params) {\n");
        $this->indent();
        $this->_segments[] =  'function';
    }

    public function doComment($comment)
    {
        $comment = str_replace('*/', '* /', $comment);
        $this->pushCode("/* $comment */");
    }

    public function doEval($code)
    {
        $this->pushCode($code);
    }

    public function doForeach($out, $source)
    {
        $this->_segments[] =  'foreach';
        $this->pushCode("foreach ($source as $out):");
        $this->indent();
    }

    public function doEnd($expects = NULL)
    {
        if (!count($this->_segments)) {
            if (!$expects) $expects = 'anything';
            throw new PHPTAL_Exception("Bug: CodeWriter generated end of block without $expects open");
        }
                
        $segment = array_pop($this->_segments);
        if ($expects !== NULL && $segment !== $expects) {
            throw new PHPTAL_Exception("Bug: CodeWriter generated end of $expects, but needs to close $segment");
        }
        
        $this->unindent();
        if ($segment == 'function') {
            $this->pushCode("\n}\n\n");
            $functionCode = $this->getResult();
            $this->popCodeWriterContext();
            $this->_result = $functionCode . $this->_result;
        } elseif ($segment == 'try')
            $this->pushCode('}');
        elseif ($segment == 'catch')
            $this->pushCode('}');
        else
            $this->pushCode("end$segment");
    }

    public function doTry()
    {
        $this->_segments[] =  'try';
        $this->pushCode('try {');
        $this->indent();
    }

    public function doSetVar($varname, $code)
    {
        $this->pushCode($varname.' = '.$code);
    }

    public function doCatch($catch)
    {
        $this->doEnd('try');
        $this->_segments[] =  'catch';
        $this->pushCode('catch('.$catch.') {');
        $this->indent();
    }

    public function doIf($condition)
    {
        $this->_segments[] =  'if';
        $this->pushCode('if ('.$condition.'): ');
        $this->indent();
    }

    public function doElseIf($condition)
    {
        if (end($this->_segments) !== 'if') {
            throw new PHPTAL_Exception("Bug: CodeWriter generated elseif without if");
        }
        $this->unindent();
        $this->pushCode('elseif ('.$condition.'): ');
        $this->indent();
    }

    public function doElse()
    {
        if (end($this->_segments) !== 'if') {
            throw new PHPTAL_Exception("Bug: CodeWriter generated else without if");
        }        
        $this->unindent();
        $this->pushCode('else: ');
        $this->indent();
    }

    public function doEcho($code)
    {
        if ($code === "''") return;
        $this->flush();
        $this->pushCode('echo '.$this->escapeCode($code));
    }

    public function doEchoRaw($code)
    {
        if ($code === "''") return;
        $this->pushCode('echo '.$this->stringifyCode($this->interpolateHTML($code)));
    }

    public function interpolateHTML($html)
    {
        return $this->_state->interpolateTalesVarsInHtml($html);
    }

    public function interpolateCDATA($str)
    {
        return $this->_state->interpolateTalesVarsInCDATA($str);
    }

    public function pushHTML($html)
    {
        if ($html === "") return;
        $this->flushCode();
        $this->_htmlBuffer[] =  $html;
    }

    public function pushCode($codeLine)
    {
        $this->flushHtml();
        $codeLine = $this->indentSpaces() . $codeLine;
        $this->_codeBuffer[] =  $codeLine;
    }

    /**
     * php string with escaped text
     */
    public function str($string)
    {
        return '\''.str_replace('\'', '\\\'', $string).'\'';
    }

    public function escapeCode($code)
    {
        return $this->_state->htmlchars($code);
    }

    public function stringifyCode($code)
    {
        return $this->_state->stringify($code);
    }

    public function getEncoding()
    {
        return $this->_state->getEncoding();
    }

    public function interpolateTalesVarsInString($src)
    {
        return $this->_state->interpolateTalesVarsInString($src);
    }

    public function setDebug($bool)
    {
        return $this->_state->setDebug($bool);
    }

    public function isDebugOn()
    {
        return $this->_state->isDebugOn();
    }

    public function getOutputMode()
    {
        return $this->_state->getOutputMode();
    }

    public function quoteAttributeValue($value)
    {
        if ($this->getEncoding() == 'UTF-8') // HTML 5: 8.1.2.3 Attributes ; http://code.google.com/p/html5lib/issues/detail?id=93
        {
            // regex excludes unicode control characters, all kinds of whitespace and unsafe characters
            $attr_regex = '/^[^$&\/=\'"><\s`\pM\pC\pZ\p{Pc}\p{Sk}]+$/u'; // FIXME: interpolation is done _after_ that function, so $ must be forbidden for now
        } else {
            $attr_regex = '/^[^$&\/=\'"><\s`\0177-\377]+$/';
        }

        if ($this->getOutputMode() == PHPTAL::HTML5 && preg_match($attr_regex, $value))
            return $value;
        else return '"'.$value.'"';
    }

    public function pushContext()
    {
        $this->doSetVar('$ctx', '$tpl->pushContext()');
    }

    public function popContext()
    {
        $this->doSetVar('$ctx', '$tpl->popContext()');
    }

    // ~~~~~ Private members ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    private function indentSpaces()
    {
        return str_repeat("\t", $this->_indent);
    }

    private function pushCodeWriterContext()
    {
        $this->_contexts[] =  clone $this;
        $this->_result = "";
        $this->_indent = 0;
        $this->_codeBuffer = array();
        $this->_htmlBuffer = array();
        $this->_segments = array();
    }

    private function popCodeWriterContext()
    {
        $oldContext = array_pop($this->_contexts);
        $this->_result = $oldContext->_result;
        $this->_indent = $oldContext->_indent;
        $this->_codeBuffer = $oldContext->_codeBuffer;
        $this->_htmlBuffer = $oldContext->_htmlBuffer;
        $this->_segments = $oldContext->_segments;
    }

    private $_state;
    private $_result = "";
    private $_indent = 0;
    private $_codeBuffer = array();
    private $_htmlBuffer = array();
    private $_segments = array();
    private $_contexts = array();
    private $_functionPrefix = "";
    private $_doctype = "";
    private $_xmldeclaration = "";
}