<?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
*/

/**
* @formatter number
* @max_attributes 4
*/
class Wact_Template_Formatter_number extends Wact_Template_Compiler_Formatter {

    function prepare() {
        if (count($this->parameters) == 3) {
            throw new exception('You must specify the fourth parameter');
        }
    }

    /**
    * Return this value as a PHP value
    * @return String
    */
    function getValue() {
        if ($this->isConstant()) {
            if (array_key_exists(1, $this->parameters)) {
                $places = (int)$this->parameters[1]->getValue();
            } else {
                $places = 0;
            }
            if (array_key_exists(2, $this->parameters) && array_key_exists(3, $this->parameters)) {
                $decimal = $this->parameters[2]->getValue();
                $thousep = $this->parameters[3]->getValue();
            } else {
                $decimal = '.';
                $thousep = ',';
            }
            return number_format($this->parameters[0]->getValue(), $places, $decimal, $thousep);
        } else {
            parent::getValue();
        }
    }

    /**
    * 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) {
        $code->writePHP('number_format(');
        $this->parameters[0]->generateExpression($code);
        if (array_key_exists(1, $this->parameters)) {
            $code->writePHP(',');
            $this->parameters[1]->generateExpression($code);
        }
        if (array_key_exists(2, $this->parameters)
            && array_key_exists(3, $this->parameters)) {
            $code->writePHP(',');
            $this->parameters[2]->generateExpression($code);
            $code->writePHP(',');
            $this->parameters[3]->generateExpression($code);
        }
        $code->writePHP(')');
    }

}

?>