Package | system.utils |
---|---|
Inheritance | class CFormatter » CApplicationComponent » CComponent |
Implements | IApplicationComponent |
Subclasses | CLocalizedFormatter |
Since | 1.1.0 |
Source Code | framework/utils/CFormatter.php |
formatXyz
.
The behavior of some of them may be configured via the properties of CFormatter. For example,
by configuring dateFormat, one may control how formatDate formats the value into a date string.
formatXyz
, then its shortcut method is xyz
(case-insensitive). For example, calling $formatter->date($value)
is equivalent to calling
$formatter->formatDate($value)
.
Yii::app()->format->boolean(1)
.
You might want to replace this component with CLocalizedFormatter to enable formatting based on the
current locale settings.Property | Type | Description | Defined By |
---|---|---|---|
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent |
booleanFormat | array | the text to be displayed when formatting a boolean value. | CFormatter |
dateFormat | string | the format string to be used to format a date using PHP date() function. | CFormatter |
datetimeFormat | string | the format string to be used to format a date and time using PHP date() function. | CFormatter |
htmlPurifier | CHtmlPurifier | the HTML purifier instance | CFormatter |
htmlPurifierOptions | array | the options to be passed to CHtmlPurifier instance used in this class. | CFormatter |
isInitialized | boolean | Checks if this application component has been initialized. | CApplicationComponent |
numberFormat | array | the format used to format a number with PHP number_format() function. | CFormatter |
sizeFormat | array | the format used to format size (bytes). | CFormatter |
timeFormat | string | the format string to be used to format a time using PHP date() function. | CFormatter |
Method | Description | Defined By |
---|---|---|
__call() | Calls the format method when its shortcut is invoked. | CFormatter |
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent |
__isset() | Checks if a property value is null. | CComponent |
__set() | Sets value of a component property. | CComponent |
__unset() | Sets a component property to be null. | CComponent |
asa() | Returns the named behavior object. | CComponent |
attachBehavior() | Attaches a behavior to this component. | CComponent |
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent |
attachEventHandler() | Attaches an event handler to an event. | CComponent |
canGetProperty() | Determines whether a property can be read. | CComponent |
canSetProperty() | Determines whether a property can be set. | CComponent |
detachBehavior() | Detaches a behavior from the component. | CComponent |
detachBehaviors() | Detaches all behaviors from the component. | CComponent |
detachEventHandler() | Detaches an existing event handler. | CComponent |
disableBehavior() | Disables an attached behavior. | CComponent |
disableBehaviors() | Disables all behaviors attached to this component. | CComponent |
enableBehavior() | Enables an attached behavior. | CComponent |
enableBehaviors() | Enables all behaviors attached to this component. | CComponent |
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent |
format() | Formats a value based on the given type. | CFormatter |
formatBoolean() | Formats the value as a boolean. | CFormatter |
formatDate() | Formats the value as a date. | CFormatter |
formatDatetime() | Formats the value as a date and time. | CFormatter |
formatEmail() | Formats the value as a mailto link. | CFormatter |
formatHtml() | Formats the value as HTML text without any encoding. | CFormatter |
formatImage() | Formats the value as an image tag. | CFormatter |
formatNtext() | Formats the value as a HTML-encoded plain text and converts newlines with HTML <br /> or | CFormatter |
formatNumber() | Formats the value as a number using PHP number_format() function. | CFormatter |
formatRaw() | Formats the value as is without any formatting. | CFormatter |
formatSize() | Formats the value in bytes as a size in human readable form. | CFormatter |
formatText() | Formats the value as a HTML-encoded plain text. | CFormatter |
formatTime() | Formats the value as a time. | CFormatter |
formatUrl() | Formats the value as a hyperlink. | CFormatter |
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent |
getHtmlPurifier() | Returns the HTML purifier instance | CFormatter |
getIsInitialized() | Checks if this application component has been initialized. | CApplicationComponent |
hasEvent() | Determines whether an event is defined. | CComponent |
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent |
hasProperty() | Determines whether a property is defined. | CComponent |
init() | Initializes the application component. | CApplicationComponent |
raiseEvent() | Raises an event. | CComponent |
Method | Description | Defined By |
---|---|---|
normalizeDateValue() | Normalizes an expression as a timestamp. | CFormatter |
the text to be displayed when formatting a boolean value. The first element corresponds
to the text display for false, the second element for true. Defaults to array('No', 'Yes')
.
the format string to be used to format a date using PHP date() function. Defaults to 'Y/m/d'.
the format string to be used to format a date and time using PHP date() function. Defaults to 'Y/m/d h:i:s A'.
the HTML purifier instance
the options to be passed to CHtmlPurifier instance used in this class. CHtmlPurifier is used in formatHtml method, so this property could be useful to customize HTML filtering behavior.
the format used to format a number with PHP number_format() function. Three elements may be specified: "decimals", "decimalSeparator" and "thousandSeparator". They correspond to the number of digits after the decimal point, the character displayed as the decimal point and the thousands separator character.
the format used to format size (bytes). Three elements may be specified: "base", "decimals" and "decimalSeparator". They correspond to the base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte, defaults to 1024), the number of digits after the decimal point (defaults to 2) and the character displayed as the decimal point. "decimalSeparator" is available since version 1.1.13
the format string to be used to format a time using PHP date() function. Defaults to 'h:i:s A'.
public mixed __call(string $name, array $parameters)
| ||
$name | string | the method name |
$parameters | array | method parameters |
{return} | mixed | the method return value |
public function __call($name,$parameters)
{
if(method_exists($this,'format'.$name))
return call_user_func_array(array($this,'format'.$name),$parameters);
else
return parent::__call($name,$parameters);
}
Calls the format method when its shortcut is invoked. This is a PHP magic method that we override to implement the shortcut format methods.
public string format(mixed $value, string $type)
| ||
$value | mixed | the value to be formatted |
$type | string | the data type. This must correspond to a format method available in CFormatter. For example, we can use 'text' here because there is method named formatText. |
{return} | string | the formatted data |
public function format($value,$type)
{
$method='format'.$type;
if(method_exists($this,$method))
return $this->$method($value);
else
throw new CException(Yii::t('yii','Unknown type "{type}".',array('{type}'=>$type)));
}
Formats a value based on the given type.
public string formatBoolean(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatBoolean($value)
{
return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
}
Formats the value as a boolean.
public string formatDate(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatDate($value)
{
return date($this->dateFormat,$this->normalizeDateValue($value));
}
Formats the value as a date.
public string formatDatetime(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatDatetime($value)
{
return date($this->datetimeFormat,$this->normalizeDateValue($value));
}
Formats the value as a date and time.
public string formatEmail(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatEmail($value)
{
return CHtml::mailto($value);
}
Formats the value as a mailto link.
public string formatHtml(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatHtml($value)
{
return $this->getHtmlPurifier()->purify($value);
}
Formats the value as HTML text without any encoding.
public string formatImage(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatImage($value)
{
return CHtml::image($value);
}
Formats the value as an image tag.
public string formatNtext(mixed $value, boolean $paragraphs=false, boolean $removeEmptyParagraphs=true)
| ||
$value | mixed | the value to be formatted |
$paragraphs | boolean | whether newlines should be converted to HTML <p></p> tags, false by default meaning that HTML <br /> tags will be used |
$removeEmptyParagraphs | boolean | whether empty paragraphs should be removed, defaults to true; makes sense only when $paragraphs parameter is true |
{return} | string | the formatted result |
public function formatNtext($value,$paragraphs=false,$removeEmptyParagraphs=true)
{
$value=CHtml::encode($value);
if($paragraphs)
{
$value='<p>'.str_replace(array("\r\n", "\n", "\r"), '</p><p>',$value).'</p>';
if($removeEmptyParagraphs)
$value=preg_replace('/(<\/p><p>){2,}/i','</p><p>',$value);
return $value;
}
else
{
return nl2br($value);
}
}
Formats the value as a HTML-encoded plain text and converts newlines with HTML <br /> or <p></p> tags.
public string formatNumber(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatNumber($value)
{
return number_format($value,$this->numberFormat['decimals'],$this->numberFormat['decimalSeparator'],$this->numberFormat['thousandSeparator']);
}
Formats the value as a number using PHP number_format() function.
public string formatRaw(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatRaw($value)
{
return $value;
}
Formats the value as is without any formatting. This method simply returns back the parameter without any format.
public string formatSize(integer $value, boolean $verbose=false)
| ||
$value | integer | value in bytes to be formatted |
$verbose | boolean | if full names should be used (e.g. bytes, kilobytes, ...). Defaults to false meaning that short names will be used (e.g. B, KB, ...). |
{return} | string | the formatted result |
public function formatSize($value,$verbose=false)
{
$base=$this->sizeFormat['base'];
for($i=0; $base<=$value && $i<5; $i++)
$value=$value/$base;
$value=round($value, $this->sizeFormat['decimals']);
$formattedValue=isset($this->sizeFormat['decimalSeparator']) ? str_replace('.',$this->sizeFormat['decimalSeparator'],$value) : $value;
$params=array($value,'{n}'=>$formattedValue);
switch($i)
{
case 0:
return $verbose ? Yii::t('yii','{n} byte|{n} bytes',$params) : Yii::t('yii', '{n} B',$params);
case 1:
return $verbose ? Yii::t('yii','{n} kilobyte|{n} kilobytes',$params) : Yii::t('yii','{n} KB',$params);
case 2:
return $verbose ? Yii::t('yii','{n} megabyte|{n} megabytes',$params) : Yii::t('yii','{n} MB',$params);
case 3:
return $verbose ? Yii::t('yii','{n} gigabyte|{n} gigabytes',$params) : Yii::t('yii','{n} GB',$params);
default:
return $verbose ? Yii::t('yii','{n} terabyte|{n} terabytes',$params) : Yii::t('yii','{n} TB',$params);
}
}
Formats the value in bytes as a size in human readable form.
public string formatText(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatText($value)
{
return CHtml::encode($value);
}
Formats the value as a HTML-encoded plain text.
public string formatTime(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatTime($value)
{
return date($this->timeFormat,$this->normalizeDateValue($value));
}
Formats the value as a time.
public string formatUrl(mixed $value)
| ||
$value | mixed | the value to be formatted |
{return} | string | the formatted result |
public function formatUrl($value)
{
$url=$value;
if(strpos($url,'http://')!==0 && strpos($url,'https://')!==0)
$url='http://'.$url;
return CHtml::link(CHtml::encode($value),$url);
}
Formats the value as a hyperlink.
public CHtmlPurifier getHtmlPurifier()
| ||
{return} | CHtmlPurifier | the HTML purifier instance |
public function getHtmlPurifier()
{
if($this->_htmlPurifier===null)
$this->_htmlPurifier=new CHtmlPurifier;
$this->_htmlPurifier->options=$this->htmlPurifierOptions;
return $this->_htmlPurifier;
}
protected int normalizeDateValue(mixed $time)
| ||
$time | mixed | the time expression to be normalized |
{return} | int | the normalized result as a UNIX timestamp |
protected function normalizeDateValue($time)
{
if(is_string($time))
{
if(ctype_digit($time) || ($time[0]=='-' && ctype_digit(substr($time, 1))))
return (int)$time;
else
return strtotime($time);
}
elseif (class_exists('DateTime', false) && $time instanceof DateTime)
return $time->getTimestamp();
else
return (int)$time;
}
Normalizes an expression as a timestamp.
Change default CFormatter values.
The default CFormatter (id: 'format') is not (yet) linked to locales.
To change the values used by this default formatter you can add the following code to your main.php config file.
'components'=>array( ... 'format'=>array( 'booleanFormat'=>array('Notext','Yestext'), ... ), ... ),
HOW to Format Numbers (decimals)
this is how I format numbers....
$formatter = new CFormatter; $formatter->numberFormat = array('decimals'=>'2','decimalSeparator'=>'.'); $ra->importe = $formatter->number($item->importe_neto - $item->importe_pagado); $ra->intereses = $formatter->number(0);
Format datetime string instead of timestamp
(When using CGridView/CDetailView) you may want to format a date string (ie: mysql datetime field) instead of a timestamp.
You can use this:
array( 'name' => 'startsOn', 'format' => 'datetime', 'value' => 'strtotime($data->startsOn)' ),
Or use this:
array( 'name' => 'startsOn', 'value' => 'Yii::app()->dateFormatter->formatDateTime(strtotime($data->startsOn))' ),
CLocalizedFormatter
Since Yii 1.1.14, a CLocalizedFormatter is available.
To replace the application component 'format', which is registered by CApplication by default, you can put this in your application 'components' config:
'format' => array('class' => 'CLocalizedFormatter'),
Signup or Login in order to comment.