summaryrefslogtreecommitdiff
path: root/framework/Util/TDataValueFormatter.php
blob: 797a88d180a08113bf7f71de45762c3a25b4b7fa (plain)
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
<?php
/**
 * TDataValueFormatter class file
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.pradosoft.com/
 * @copyright Copyright &copy; 2005 PradoSoft
 * @license http://www.pradosoft.com/license/
 * @version $Revision: $  $Date: $
 * @package System.Util
 */

/**
 * TDataValueFormatter class
 *
 * TDataValueFormatter is a utility class that formats a data value
 * according to a format string.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @version $Revision: $  $Date: $
 * @package System.Util
 * @since 3.0
 */
class TDataValueFormatter
{
	/**
	 * Formats the text value according to a format string.
	 * If the format string is empty, the original value is converted into
	 * a string and returned.
	 * If the format string starts with '#', the string is treated as a PHP expression
	 * within which the token '{0}' is translated with the data value to be formated.
	 * Otherwise, the format string and the data value are passed
	 * as the first and second parameters in {@link sprintf}.
	 * @param string format string
	 * @param mixed the data associated with the cell
	 * @param TComponent the context to evaluate the expression
	 * @return string the formatted result
	 */
	public static function format($formatString,$value,$context=null)
	{
		if($formatString==='')
			return TPropertyValue::ensureString($value);
		else if($formatString[0]==='#')
		{
			$expression=strtr(substr($formatString,1),array('{0}'=>'$value'));
			if($context instanceof TComponent)
				return $context->evaluateExpression($expression);
			else
			{
				try
				{
					if(eval("\$result=$expression;")===false)
						throw new Exception('');
					return $result;
				}
				catch(Exception $e)
				{
					throw new TInvalidOperationException('datavalueformatter_expression_invalid',$expression,$e->getMessage());
				}
			}
		}
		else
			return sprintf($formatString,$value);
	}
}

?>