<?php
/**
* Web Application Component Toolkit
*
* @link http://www.phpwact.org/
*
* @author Wact Development Team
* @link http://www.phpwact.org/team
*
* @copyright Copyright 2006, Jeff Moore
* @license http://opensource.org/licenses/mit-license.php MIT
*/

/**
* Used to store attribute expressions found inside tag components
*/
class Wact_Template_Compiler_Attribute_Expression {

    /**
    */
    public $name;

    /**
    */
    protected $expression;

    /**
    */
    function __construct($name, $expression) {
        $this->name = $name;
        $this->expression = $expression;
    }

    /**
    * Can a PHP value for this reference be calculated at compile time?
    * @return Boolean
    */
    function isConstant() {
        return $this->expression->isConstant();
    }

    /**
    * Return the value of this attribute, usually for further prossing.
    * @return String
    */
    function getValue() {
        return $this->expression->getValue();
    }

    /**
    * Return the value of this attribute, usually for further prossing.
    * @return String
    */
    function getValueEscaped() {
        return htmlspecialchars($this->expression->getValue(), ENT_QUOTES);
    }

    /**
    * Generate the code to output this attribute as part of a tag.
    * @param CodeWriter
    * @return void
    */
    function generate($code) {
        $code->writeHTML(' ' . $this->name);
        $code->writeHTML('="');
        if ($this->isConstant()) {
            $value = $this->getValue();
            if (!is_null($value)) {
                $code->writeHTML(htmlspecialchars($value, ENT_QUOTES));
            }
        } else {
            $this->expression->generatePreStatement($code);
            $code->writePHP('echo htmlspecialchars(');
            $this->expression->generateExpression($code);
            $code->writePHP(', ENT_QUOTES);');
            $this->expression->generatePostStatement($code);
        }
        $code->writeHTML('"');
    }

    /**
    * Generate setup code for an expression reference
    * @param CodeWriter
    * @return void
    */
    function generatePreStatement($code) {
        $this->expression->generatePreStatement($code);
    }

    /**
    * Generate the code to read the data value at run time
    * Must generate only a valid PHP Expression.
    * @param CodeWriter
    * @return void
    */
    function generateExpression($code) {
        $this->expression->generateExpression($code);
    }

    /**
    * Generate tear down code for an expression reference
    * @param CodeWriter
    * @return void
    */
    function generatePostStatement($code) {
        $this->expression->generatePostStatement($code);
    }

    /**
    * Prepare this attribute to be used
    * @return void
    */
    function prepare() {
        return $this->expression->prepare();
    }

}

?>