Class yii\i18n\Formatter

Inheritanceyii\i18n\Formatter » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Subclassesluya\components\Formatter
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/i18n/Formatter.php

Formatter provides a set of commonly used data formatting methods.

The formatting methods provided by Formatter are all named in the form of asXyz(). The behavior of some of them may be configured via the properties of Formatter. For example, by configuring $dateFormat, one may control how asDate() formats the value into a date string.

Formatter is configured as an application component in yii\base\Application by default. You can access that instance via Yii::$app->formatter.

The Formatter class is designed to format values according to a $locale. For this feature to work the PHP intl extension has to be installed. Most of the methods however work also if the PHP intl extension is not installed by providing a fallback implementation. Without intl month and day names are in English only. Note that even if the intl extension is installed, formatting date and time values for years >=2038 or <=1901 on 32bit systems will fall back to the PHP implementation because intl uses a 32bit UNIX timestamp internally. On a 64bit system the intl formatter is used in all cases if installed.

Note: The Formatter class is meant to be used for formatting values for display to users in different languages and time zones. If you need to format a date or time in machine readable format, use the PHP date() function instead.

Public Properties

Hide inherited properties

Property Type Description Defined By
$baseUnits array The base units that are used as multipliers for smallest possible unit from $measureUnits. yii\i18n\Formatter
$behaviors yii\base\Behavior[] List of behaviors attached to this component. yii\base\Component
$booleanFormat array The text to be displayed when formatting a boolean value. yii\i18n\Formatter
$calendar IntlCalendar|integer|null The calendar to be used for date formatting. yii\i18n\Formatter
$currencyCode string|null The 3-letter ISO 4217 currency code indicating the default currency to use for asCurrency(). yii\i18n\Formatter
$currencyDecimalSeparator string|null The character displayed as the decimal point when formatting a currency. yii\i18n\Formatter
$dateFormat string The default format string to be used to format a date. yii\i18n\Formatter
$datetimeFormat string The default format string to be used to format a date and time. yii\i18n\Formatter
$decimalSeparator string|null The character displayed as the decimal point when formatting a number. yii\i18n\Formatter
$defaultTimeZone string The time zone that is assumed for input values if they do not include a time zone explicitly. yii\i18n\Formatter
$language string|null The language code (e.g. en-US, en) that is used to translate internal messages. yii\i18n\Formatter
$locale string|null The locale ID that is used to localize the date and number formatting. yii\i18n\Formatter
$measureUnits array Configuration of weight and length measurement units. yii\i18n\Formatter
$nullDisplay string|null The text to be displayed when formatting a null value. yii\i18n\Formatter
$numberFormatterOptions array A list of name value pairs that are passed to the intl NumberFormatter::setAttribute() method of all the number formatter objects created by createNumberFormatter(). yii\i18n\Formatter
$numberFormatterSymbols array A list of name value pairs that are passed to the intl NumberFormatter::setSymbol() method of all the number formatter objects created by createNumberFormatter(). yii\i18n\Formatter
$numberFormatterTextOptions array A list of name value pairs that are passed to the intl NumberFormatter::setTextAttribute() method of all the number formatter objects created by createNumberFormatter(). yii\i18n\Formatter
$sizeFormatBase integer The base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by asSize() and asShortSize(). yii\i18n\Formatter
$systemOfUnits string Default system of measure units. yii\i18n\Formatter
$thousandSeparator string|null The character displayed as the thousands separator (also called grouping separator) character when formatting a number. yii\i18n\Formatter
$timeFormat string The default format string to be used to format a time. yii\i18n\Formatter
$timeZone string|null The time zone to use for formatting time and date values. yii\i18n\Formatter

Public Methods

Hide inherited methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
asBoolean() Formats the value as a boolean. yii\i18n\Formatter
asCurrency() Formats the value as a currency number. yii\i18n\Formatter
asDate() Formats the value as a date. yii\i18n\Formatter
asDatetime() Formats the value as a datetime. yii\i18n\Formatter
asDecimal() Formats the value as a decimal number. yii\i18n\Formatter
asDuration() Represents the value as duration in human readable format. yii\i18n\Formatter
asEmail() Formats the value as a mailto link. yii\i18n\Formatter
asHtml() Formats the value as HTML text. yii\i18n\Formatter
asImage() Formats the value as an image tag. yii\i18n\Formatter
asInteger() Formats the value as an integer number by removing any decimal digits without rounding. yii\i18n\Formatter
asLength() Formats the value as a length in human readable form for example 12 meters. yii\i18n\Formatter
asNtext() Formats the value as an HTML-encoded plain text with newlines converted into breaks. yii\i18n\Formatter
asOrdinal() Formats the value as a ordinal value of a number. yii\i18n\Formatter
asParagraphs() Formats the value as HTML-encoded text paragraphs. yii\i18n\Formatter
asPercent() Formats the value as a percent number with "%" sign. yii\i18n\Formatter
asRaw() Formats the value as is without any formatting. yii\i18n\Formatter
asRelativeTime() Formats the value as the time interval between a date and now in human readable form. yii\i18n\Formatter
asScientific() Formats the value as a scientific number. yii\i18n\Formatter
asShortLength() Formats the value as a length in human readable form for example 12 m. yii\i18n\Formatter
asShortSize() Formats the value in bytes as a size in human readable form for example 12 kB. yii\i18n\Formatter
asShortWeight() Formats the value as a weight in human readable form for example 12 kg. yii\i18n\Formatter
asSize() Formats the value in bytes as a size in human readable form, for example 12 kilobytes. yii\i18n\Formatter
asSpellout() Formats the value as a number spellout. yii\i18n\Formatter
asText() Formats the value as an HTML-encoded plain text. yii\i18n\Formatter
asTime() Formats the value as a time. yii\i18n\Formatter
asTimestamp() Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970). yii\i18n\Formatter
asUrl() Formats the value as a hyperlink. yii\i18n\Formatter
asWeight() Formats the value as a weight in human readable form for example 12 kilograms. yii\i18n\Formatter
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
format() Formats the value based on the given format type. yii\i18n\Formatter
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. yii\i18n\Formatter
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
trigger() Triggers an event. yii\base\Component

Protected Methods

Hide inherited methods

Method Description Defined By
asCurrencyStringFallback() Fallback for formatting value as a currency number. yii\i18n\Formatter
asDecimalStringFallback() Fallback for formatting value as a decimal number. yii\i18n\Formatter
asIntegerStringFallback() Fallback for formatting value as an integer number by removing any decimal digits without rounding. yii\i18n\Formatter
asPercentStringFallback() Fallback for formatting value as a percent number with "%" sign. yii\i18n\Formatter
createNumberFormatter() Creates a number formatter based on the given type and format. yii\i18n\Formatter
formatNumber() Given the value in bytes formats number part of the human readable form. yii\i18n\Formatter
isNormalizedValueMispresented() Checks if string representations of given value and its normalized version are different. yii\i18n\Formatter
normalizeDatetimeValue() Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods. yii\i18n\Formatter
normalizeNumericStringValue() Normalizes a numeric string value. yii\i18n\Formatter
normalizeNumericValue() Normalizes a numeric input value. yii\i18n\Formatter

Constants

Hide inherited constants

Constant Value Description Defined By
FORMAT_WIDTH_LONG 'long' yii\i18n\Formatter
FORMAT_WIDTH_SHORT 'short' yii\i18n\Formatter
UNIT_LENGTH 'length' yii\i18n\Formatter
UNIT_SYSTEM_IMPERIAL 'imperial' yii\i18n\Formatter
UNIT_SYSTEM_METRIC 'metric' yii\i18n\Formatter
UNIT_WEIGHT 'mass' yii\i18n\Formatter

Property Details

Hide inherited properties

$baseUnits public property (available since version 2.0.13)

The base units that are used as multipliers for smallest possible unit from $measureUnits.

public array $baseUnits = [
    
self::UNIT_LENGTH => [
        
self::UNIT_SYSTEM_IMPERIAL => 12,
        
self::UNIT_SYSTEM_METRIC => 1000,
    ],
    
self::UNIT_WEIGHT => [
        
self::UNIT_SYSTEM_IMPERIAL => 7000,
        
self::UNIT_SYSTEM_METRIC => 1000,
    ],
]
$booleanFormat public property

The text to be displayed when formatting a boolean value. The first element corresponds to the text displayed for false, the second element for true. Defaults to ['No', 'Yes'], where Yes and No will be translated according to $locale.

public array $booleanFormat null
$calendar public property (available since version 2.0.7)

The calendar to be used for date formatting. The value of this property will be directly passed to the constructor of the IntlDateFormatter class.

Defaults to null, which means the Gregorian calendar will be used. You may also explicitly pass the constant \IntlDateFormatter::GREGORIAN for Gregorian calendar.

To use an alternative calendar like for example the Jalali calendar, set this property to \IntlDateFormatter::TRADITIONAL. The calendar must then be specified in the $locale, for example for the persian calendar the configuration for the formatter would be:

'formatter' => [
    'locale' => 'fa_IR@calendar=persian',
    'calendar' => \IntlDateFormatter::TRADITIONAL,
],

Available calendar names can be found in the ICU manual.

Since PHP 5.5 you may also use an instance of the IntlCalendar class. Check the PHP manual for more details.

If the PHP intl extension is not available, setting this property will have no effect.

See also:

$currencyCode public property

The 3-letter ISO 4217 currency code indicating the default currency to use for asCurrency(). If not set, the currency code corresponding to $locale will be used. Note that in this case the $locale has to be specified with a country code, e.g. en-US otherwise it is not possible to determine the default currency.

public string|null $currencyCode null
$currencyDecimalSeparator public property (available since version 2.0.35)

The character displayed as the decimal point when formatting a currency. If not set, the currency decimal separator corresponding to $locale will be used. If PHP intl extension is not available, setting this property will have no effect.

$dateFormat public property

The default format string to be used to format a date. This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.

It can also be a custom format as specified in the ICU manual. Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function.

For example:

'MM/dd/yyyy' // date in ICU format
'php:m/d/Y' // the same date in PHP format
public string $dateFormat 'medium'
$datetimeFormat public property

The default format string to be used to format a date and time. This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.

It can also be a custom format as specified in the ICU manual.

Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date() function.

For example:

'MM/dd/yyyy HH:mm:ss' // date and time in ICU format
'php:m/d/Y H:i:s' // the same date and time in PHP format
public string $datetimeFormat 'medium'
$decimalSeparator public property

The character displayed as the decimal point when formatting a number. If not set, the decimal separator corresponding to $locale will be used. If PHP intl extension is not available, the default value is '.'.

$defaultTimeZone public property (available since version 2.0.1)

The time zone that is assumed for input values if they do not include a time zone explicitly.

The value must be a valid time zone identifier, e.g. UTC, Europe/Berlin or America/Chicago. Please refer to the php manual for available time zones.

It defaults to UTC so you only have to adjust this value if you store datetime values in another time zone in your database.

Note that a UNIX timestamp is always in UTC by its definition. That means that specifying a default time zone different from UTC has no effect on date values given as UNIX timestamp.

public string $defaultTimeZone 'UTC'
$language public property (available since version 2.0.28)

The language code (e.g. en-US, en) that is used to translate internal messages. If not set, $locale will be used (without the @calendar param, if included).

public string|null $language null
$locale public property

The locale ID that is used to localize the date and number formatting. For number and date formatting this is only effective when the PHP intl extension is installed. If not set, yii\base\Application::$language will be used.

public string|null $locale null
$measureUnits public property (available since version 2.0.13)

Configuration of weight and length measurement units. This array contains the most usable measurement units, but you can change it in case you have some special requirements.

For example, you can add smaller measure unit:

$this->measureUnits[self::UNIT_LENGTH][self::UNIT_SYSTEM_METRIC] = [
    'nanometer' => 0.000001
]

See also:

public array $measureUnits = [
    
self::UNIT_LENGTH => [
        
self::UNIT_SYSTEM_IMPERIAL => [
            
'inch' => 1,
            
'foot' => 12,
            
'yard' => 36,
            
'chain' => 792,
            
'furlong' => 7920,
            
'mile' => 63360,
        ],
        
self::UNIT_SYSTEM_METRIC => [
            
'millimeter' => 1,
            
'centimeter' => 10,
            
'meter' => 1000,
            
'kilometer' => 1000000,
        ],
    ],
    
self::UNIT_WEIGHT => [
        
self::UNIT_SYSTEM_IMPERIAL => [
            
'grain' => 1,
            
'drachm' => 27.34375,
            
'ounce' => 437.5,
            
'pound' => 7000,
            
'stone' => 98000,
            
'quarter' => 196000,
            
'hundredweight' => 784000,
            
'ton' => 15680000,
        ],
        
self::UNIT_SYSTEM_METRIC => [
            
'gram' => 1,
            
'kilogram' => 1000,
            
'ton' => 1000000,
        ],
    ],
]
$nullDisplay public property

The text to be displayed when formatting a null value. Defaults to '<span class="not-set">(not set)</span>', where (not set) will be translated according to $locale.

public string|null $nullDisplay null
$numberFormatterOptions public property

A list of name value pairs that are passed to the intl NumberFormatter::setAttribute() method of all the number formatter objects created by createNumberFormatter(). This property takes only effect if the PHP intl extension is installed.

Please refer to the PHP manual for the possible options.

For example to adjust the maximum and minimum value of fraction digits you can configure this property like the following:

[
    NumberFormatter::MIN_FRACTION_DIGITS => 0,
    NumberFormatter::MAX_FRACTION_DIGITS => 2,
]
$numberFormatterSymbols public property (available since version 2.0.4)

A list of name value pairs that are passed to the intl NumberFormatter::setSymbol() method of all the number formatter objects created by createNumberFormatter(). This property takes only effect if the PHP intl extension is installed.

Please refer to the PHP manual for the possible options.

For example to choose a custom currency symbol, e.g. U+20BD instead of руб. for Russian Ruble:

[
    NumberFormatter::CURRENCY_SYMBOL => '₽',
]
$numberFormatterTextOptions public property

A list of name value pairs that are passed to the intl NumberFormatter::setTextAttribute() method of all the number formatter objects created by createNumberFormatter(). This property takes only effect if the PHP intl extension is installed.

Please refer to the PHP manual for the possible options.

For example to change the minus sign for negative numbers you can configure this property like the following:

[
    NumberFormatter::NEGATIVE_PREFIX => 'MINUS',
]
$sizeFormatBase public property

The base at which a kilobyte is calculated (1000 or 1024 bytes per kilobyte), used by asSize() and asShortSize(). Defaults to 1024.

public integer $sizeFormatBase 1024
$systemOfUnits public property (available since version 2.0.13)

Default system of measure units. Defaults to UNIT_SYSTEM_METRIC. Possible values:

See also:

public string $systemOfUnits self::UNIT_SYSTEM_METRIC
$thousandSeparator public property

The character displayed as the thousands separator (also called grouping separator) character when formatting a number. If not set, the thousand separator corresponding to $locale will be used. If PHP intl extension is not available, the default value is ','.

$timeFormat public property

The default format string to be used to format a time. This can be "short", "medium", "long", or "full", which represents a preset format of different lengths.

It can also be a custom format as specified in the ICU manual. Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function.

For example:

'HH:mm:ss' // time in ICU format
'php:H:i:s' // the same time in PHP format
public string $timeFormat 'medium'
$timeZone public property

The time zone to use for formatting time and date values.

This can be any value that may be passed to date_default_timezone_set() e.g. UTC, Europe/Berlin or America/Chicago. Refer to the php manual for available time zones. If this property is not set, yii\base\Application::$timeZone will be used.

Note that the default time zone for input data is assumed to be UTC by default if no time zone is included in the input date value. If you store your data in a different time zone in the database, you have to adjust $defaultTimeZone accordingly.

public string|null $timeZone null

Method Details

Hide inherited methods

__call() public method

Defined in: yii\base\Component::__call()

Calls the named method which is not a class method.

This method will check if any attached behavior has the named method and will execute it if available.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() public method

Defined in: yii\base\Component::__clone()

This method is called after the object is created by cloning an existing one.

It removes all behaviors because they are attached to the old object.

public void __clone ( )

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\Component::__get()

Returns the value of a component property.

This method will check in the following order and act accordingly:

  • a property defined by a getter: return the getter result
  • a property of a behavior: return the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value or the value of a behavior's property

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only.

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\Component::__isset()

Checks if a property is set, i.e. defined and not null.

This method will check in the following order and act accordingly:

  • a property defined by a setter: return whether the property is set
  • a property of a behavior: return whether the property is set
  • return false for non existing properties

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() public method

Defined in: yii\base\Component::__set()

Sets the value of a component property.

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value
  • an event in the format of "on xyz": attach the handler to the event "xyz"
  • a behavior in the format of "as xyz": attach the behavior named as "xyz"
  • a property of a behavior: set the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only.

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__unset() public method

Defined in: yii\base\Component::__unset()

Sets a component property to be null.

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value to be null
  • a property of a behavior: set the property value to be null

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property).

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            
asBoolean() public method

Formats the value as a boolean.

See also $booleanFormat.

public string asBoolean ( $value )
$value mixed

The value to be formatted.

return string

The formatted result.

                public function asBoolean($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return $value ? $this->booleanFormat[1] : $this->booleanFormat[0];
}

            
asCurrency() public method

Formats the value as a currency number.

This function does not require the PHP intl extension to be installed to work, but it is highly recommended to install it to get good formatting results.

Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it's recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.

public string asCurrency ( $value, $currency null, $options = [], $textOptions = [] )
$value mixed

The value to be formatted.

$currency string|null

The 3-letter ISO 4217 currency code indicating the currency to use. If null, $currencyCode will be used.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

throws yii\base\InvalidConfigException

if no currency is given and $currencyCode is not defined.

                public function asCurrency($value, $currency = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asCurrencyStringFallback((string) $value, $currency);
    }
    if ($this->_intlLoaded) {
        $currency = $currency ?: $this->currencyCode;
        // currency code must be set before fraction digits
        // https://www.php.net/manual/en/numberformatter.formatcurrency.php#114376
        if ($currency && !isset($textOptions[NumberFormatter::CURRENCY_CODE])) {
            $textOptions[NumberFormatter::CURRENCY_CODE] = $currency;
        }
        $formatter = $this->createNumberFormatter(NumberFormatter::CURRENCY, null, $options, $textOptions);
        if ($currency === null) {
            $result = $formatter->format($normalizedValue);
        } else {
            $result = $formatter->formatCurrency($normalizedValue, $currency);
        }
        if ($result === false) {
            throw new InvalidArgumentException('Formatting currency value failed: ' . $formatter->getErrorCode() . ' ' . $formatter->getErrorMessage());
        }
        return $result;
    }
    if ($currency === null) {
        if ($this->currencyCode === null) {
            throw new InvalidConfigException('The default currency code for the formatter is not defined and the php intl extension is not installed which could take the default currency from the locale.');
        }
        $currency = $this->currencyCode;
    }
    return $currency . ' ' . $this->asDecimal($normalizedValue, 2, $options, $textOptions);
}

            
asCurrencyStringFallback() protected method (available since version 2.0.16)

Fallback for formatting value as a currency number.

protected string asCurrencyStringFallback ( $value, $currency null )
$value string|integer|float

The value to be formatted.

$currency string|null

The 3-letter ISO 4217 currency code indicating the currency to use. If null, $currencyCode will be used.

return string

The formatted result.

throws yii\base\InvalidConfigException

if no currency is given and $currencyCode is not defined.

                protected function asCurrencyStringFallback($value, $currency = null)
{
    if ($currency === null) {
        if ($this->currencyCode === null) {
            throw new InvalidConfigException('The default currency code for the formatter is not defined.');
        }
        $currency = $this->currencyCode;
    }
    return $currency . ' ' . $this->asDecimalStringFallback($value, 2);
}

            
asDate() public method

Formats the value as a date.

See also $dateFormat.

public string asDate ( $value, $format null )
$value integer|string|DateTime|DateTimeInterface|null

The value to be formatted. The following types of value are supported:

  • an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition.
  • a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given.
  • a PHP DateTime object. You may set the time zone for the DateTime object to specify the source time zone.

The formatter will convert date values according to $timeZone before formatting it. If no timezone conversion should be performed, you need to set $defaultTimeZone and $timeZone to the same value. Also no conversion will be performed on values that have no time information, e.g. "2017-06-05".

$format string|null

The format used to convert the value into a date string. If null, $dateFormat will be used.

This can be "short", "medium", "long", or "full", which represents a preset format of different lengths. It can also be a custom format as specified in the ICU manual.

Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value can not be evaluated as a date value.

throws yii\base\InvalidConfigException

if the date format is invalid.

                public function asDate($value, $format = null)
{
    if ($format === null) {
        $format = $this->dateFormat;
    }
    return $this->formatDateTimeValue($value, $format, 'date');
}

            
asDatetime() public method

Formats the value as a datetime.

See also $datetimeFormat.

public string asDatetime ( $value, $format null )
$value integer|string|DateTime|DateTimeInterface|null

The value to be formatted. The following types of value are supported:

  • an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition.
  • a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given.
  • a PHP DateTime object. You may set the time zone for the DateTime object to specify the source time zone.

The formatter will convert date values according to $timeZone before formatting it. If no timezone conversion should be performed, you need to set $defaultTimeZone and $timeZone to the same value.

$format string|null

The format used to convert the value into a date string. If null, $datetimeFormat will be used.

This can be "short", "medium", "long", or "full", which represents a preset format of different lengths. It can also be a custom format as specified in the ICU manual.

Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value can not be evaluated as a date value.

throws yii\base\InvalidConfigException

if the date format is invalid.

                public function asDatetime($value, $format = null)
{
    if ($format === null) {
        $format = $this->datetimeFormat;
    }
    return $this->formatDateTimeValue($value, $format, 'datetime');
}

            
asDecimal() public method

Formats the value as a decimal number.

Property $decimalSeparator will be used to represent the decimal point. The value is rounded automatically to the defined decimal digits.

Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it's recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.

See also:

public string asDecimal ( $value, $decimals null, $options = [], $textOptions = [] )
$value mixed

The value to be formatted.

$decimals integer|null

The number of digits after the decimal point. If not given, the number of digits depends in the input value and is determined based on NumberFormatter::MIN_FRACTION_DIGITS and NumberFormatter::MAX_FRACTION_DIGITS, which can be configured using $numberFormatterOptions. If the PHP intl extension is not available, the default value is 2. If you want consistent behavior between environments where intl is available and not, you should explicitly specify a value here.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

                public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asDecimalStringFallback((string) $value, $decimals);
    }
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
        if (($result = $f->format($normalizedValue)) === false) {
            throw new InvalidArgumentException('Formatting decimal value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    if ($decimals === null) {
        $decimals = 2;
    }
    return number_format($normalizedValue, $decimals, $this->decimalSeparator, $this->thousandSeparator);
}

            
asDecimalStringFallback() protected method (available since version 2.0.16)

Fallback for formatting value as a decimal number.

Property $decimalSeparator will be used to represent the decimal point. The value is rounded automatically to the defined decimal digits.

See also:

protected string asDecimalStringFallback ( $value, $decimals 2 )
$value string|integer|float

The value to be formatted.

$decimals integer|null

The number of digits after the decimal point. The default value is 2.

return string

The formatted result.

                protected function asDecimalStringFallback($value, $decimals = 2)
{
    if (empty($value)) {
        $value = 0;
    }
    $value = $this->normalizeNumericStringValue((string) $value);
    $separatorPosition = strrpos($value, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($value, 0, $separatorPosition);
        $fractionalPart = substr($value, $separatorPosition + 1);
    } else {
        $integerPart = $value;
        $fractionalPart = null;
    }
    $decimalOutput = '';
    if ($decimals === null) {
        $decimals = 2;
    }
    $carry = 0;
    if ($decimals > 0) {
        $decimalSeparator = $this->decimalSeparator;
        if ($this->decimalSeparator === null) {
            $decimalSeparator = '.';
        }
        if ($fractionalPart === null) {
            $fractionalPart = str_repeat('0', $decimals);
        } elseif (strlen($fractionalPart) > $decimals) {
            $cursor = $decimals;
            // checking if fractional part must be rounded
            if ((int) substr($fractionalPart, $cursor, 1) >= 5) {
                while (--$cursor >= 0) {
                    $carry = 0;
                    $oneUp = (int) substr($fractionalPart, $cursor, 1) + 1;
                    if ($oneUp === 10) {
                        $oneUp = 0;
                        $carry = 1;
                    }
                    $fractionalPart = substr($fractionalPart, 0, $cursor) . $oneUp . substr($fractionalPart, $cursor + 1);
                    if ($carry === 0) {
                        break;
                    }
                }
            }
            $fractionalPart = substr($fractionalPart, 0, $decimals);
        } elseif (strlen($fractionalPart) < $decimals) {
            $fractionalPart = str_pad($fractionalPart, $decimals, '0');
        }
        $decimalOutput .= $decimalSeparator . $fractionalPart;
    }
    // checking if integer part must be rounded
    if ($carry || ($decimals === 0 && $fractionalPart !== null && (int) substr($fractionalPart, 0, 1) >= 5)) {
        $integerPartLength = strlen($integerPart);
        $cursor = 0;
        while (++$cursor <= $integerPartLength) {
            $carry = 0;
            $oneUp = (int) substr($integerPart, -$cursor, 1) + 1;
            if ($oneUp === 10) {
                $oneUp = 0;
                $carry = 1;
            }
            $integerPart = substr($integerPart, 0, -$cursor) . $oneUp . substr($integerPart, $integerPartLength - $cursor + 1);
            if ($carry === 0) {
                break;
            }
        }
        if ($carry === 1) {
            $integerPart = '1' . $integerPart;
        }
    }
    if (strlen($integerPart) > 3) {
        $thousandSeparator = $this->thousandSeparator;
        if ($thousandSeparator === null) {
            $thousandSeparator = ',';
        }
        $integerPart = strrev(implode(',', str_split(strrev($integerPart), 3)));
        if ($thousandSeparator !== ',') {
            $integerPart = str_replace(',', $thousandSeparator, $integerPart);
        }
    }
    return $integerPart . $decimalOutput;
}

            
asDuration() public method (available since version 2.0.7)

Represents the value as duration in human readable format.

public string asDuration ( $value, $implodeString ', ', $negativeSign '-' )
$value DateInterval|string|integer|null

The value to be formatted. Acceptable formats:

  • DateInterval object
  • integer - number of seconds. For example: value 131 represents 2 minutes, 11 seconds
  • ISO8601 duration format. For example, all of these values represent 1 day, 2 hours, 30 minutes duration: 2015-01-01T13:00:00Z/2015-01-02T13:30:00Z - between two datetime values 2015-01-01T13:00:00Z/P1D2H30M - time interval after datetime value P1D2H30M/2015-01-02T13:30:00Z - time interval before datetime value P1D2H30M - simply a date interval P-1D2H30M - a negative date interval (-1 day, 2 hours, 30 minutes)
$implodeString string

Will be used to concatenate duration parts. Defaults to , .

$negativeSign string

Will be prefixed to the formatted duration, when it is negative. Defaults to -.

return string

The formatted duration.

                public function asDuration($value, $implodeString = ', ', $negativeSign = '-')
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    if ($value instanceof DateInterval) {
        $isNegative = $value->invert;
        $interval = $value;
    } elseif (is_numeric($value)) {
        $isNegative = $value < 0;
        $zeroDateTime = (new DateTime())->setTimestamp(0);
        $valueDateTime = (new DateTime())->setTimestamp(abs($value));
        $interval = $valueDateTime->diff($zeroDateTime);
    } elseif (strncmp($value, 'P-', 2) === 0) {
        $interval = new DateInterval('P' . substr($value, 2));
        $isNegative = true;
    } else {
        $interval = new DateInterval($value);
        $isNegative = $interval->invert;
    }
    $parts = [];
    if ($interval->y > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 year} other{# years}}', ['delta' => $interval->y], $this->language);
    }
    if ($interval->m > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 month} other{# months}}', ['delta' => $interval->m], $this->language);
    }
    if ($interval->d > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 day} other{# days}}', ['delta' => $interval->d], $this->language);
    }
    if ($interval->h > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 hour} other{# hours}}', ['delta' => $interval->h], $this->language);
    }
    if ($interval->i > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 minute} other{# minutes}}', ['delta' => $interval->i], $this->language);
    }
    if ($interval->s > 0) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 second} other{# seconds}}', ['delta' => $interval->s], $this->language);
    }
    if ($interval->s === 0 && empty($parts)) {
        $parts[] = Yii::t('yii', '{delta, plural, =1{1 second} other{# seconds}}', ['delta' => $interval->s], $this->language);
        $isNegative = false;
    }
    return empty($parts) ? $this->nullDisplay : (($isNegative ? $negativeSign : '') . implode($implodeString, $parts));
}

            
asEmail() public method

Formats the value as a mailto link.

public string asEmail ( $value, $options = [] )
$value string|null

The value to be formatted.

$options array

The tag options in terms of name-value pairs. See yii\helpers\Html::mailto().

return string

The formatted result.

                public function asEmail($value, $options = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return Html::mailto(Html::encode($value), $value, $options);
}

            
asHtml() public method

Formats the value as HTML text.

The value will be purified using yii\helpers\HtmlPurifier to avoid XSS attacks. Use asRaw() if you do not want any purification of the value.

public string asHtml ( $value, $config null )
$value string|null

The value to be formatted.

$config array|null

The configuration for the HTMLPurifier class.

return string

The formatted result.

                public function asHtml($value, $config = null)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return HtmlPurifier::process($value, $config);
}

            
asImage() public method

Formats the value as an image tag.

public string asImage ( $value, $options = [] )
$value mixed

The value to be formatted.

$options array

The tag options in terms of name-value pairs. See yii\helpers\Html::img().

return string

The formatted result.

                public function asImage($value, $options = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return Html::img($value, $options);
}

            
asInteger() public method

Formats the value as an integer number by removing any decimal digits without rounding.

Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it's recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.

public string asInteger ( $value, $options = [], $textOptions = [] )
$value mixed

The value to be formatted.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

                public function asInteger($value, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asIntegerStringFallback((string) $value);
    }
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, null, $options, $textOptions);
        $f->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
        if (($result = $f->format($normalizedValue, NumberFormatter::TYPE_INT64)) === false) {
            throw new InvalidArgumentException('Formatting integer value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    return number_format((int) $normalizedValue, 0, $this->decimalSeparator, $this->thousandSeparator);
}

            
asIntegerStringFallback() protected method (available since version 2.0.16)

Fallback for formatting value as an integer number by removing any decimal digits without rounding.

protected string asIntegerStringFallback ( $value )
$value string|integer|float

The value to be formatted.

return string

The formatted result.

                protected function asIntegerStringFallback($value)
{
    if (empty($value)) {
        $value = 0;
    }
    $value = $this->normalizeNumericStringValue((string) $value);
    $separatorPosition = strrpos($value, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($value, 0, $separatorPosition);
    } else {
        $integerPart = $value;
    }
    return $this->asDecimalStringFallback($integerPart, 0);
}

            
asLength() public method (available since version 2.0.13)

Formats the value as a length in human readable form for example 12 meters.

Check properties $baseUnits if you need to change unit of value as the multiplier of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.

See also asLength().

public string asLength ( $value, $decimals null, $numberOptions = [], $textOptions = [] )
$value float|integer

Value to be formatted.

$decimals integer|null

The number of digits after the decimal point.

$numberOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

throws yii\base\InvalidConfigException

when INTL is not installed or does not contain required information.

                public function asLength($value, $decimals = null, $numberOptions = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_LENGTH, self::FORMAT_WIDTH_LONG, $value, $decimals, $numberOptions, $textOptions);
}

            
asNtext() public method

Formats the value as an HTML-encoded plain text with newlines converted into breaks.

public string asNtext ( $value )
$value string|null

The value to be formatted.

return string

The formatted result.

                public function asNtext($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return nl2br(Html::encode($value));
}

            
asOrdinal() public method

Formats the value as a ordinal value of a number.

This function requires the PHP intl extension to be installed.

This formatter does not work well with very big numbers.

public string asOrdinal ( $value )
$value mixed

The value to be formatted

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

throws yii\base\InvalidConfigException

when the PHP intl extension is not available.

                public function asOrdinal($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $value = $this->normalizeNumericValue($value);
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::ORDINAL);
        if (($result = $f->format($value)) === false) {
            throw new InvalidArgumentException('Formatting number as ordinal failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    throw new InvalidConfigException('Format as Ordinal is only supported when PHP intl extension is installed.');
}

            
asParagraphs() public method

Formats the value as HTML-encoded text paragraphs.

Each text paragraph is enclosed within a <p> tag. One or multiple consecutive empty lines divide two paragraphs.

public string asParagraphs ( $value )
$value string|null

The value to be formatted.

return string

The formatted result.

                public function asParagraphs($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/u', "</p>\n<p>", Html::encode($value)) . '</p>');
}

            
asPercent() public method

Formats the value as a percent number with "%" sign.

Since 2.0.16 numbers that are mispresented after normalization are formatted as strings using fallback function without PHP intl extension support. For very big numbers it's recommended to pass them as strings and not use scientific notation otherwise the output might be wrong.

public string asPercent ( $value, $decimals null, $options = [], $textOptions = [] )
$value mixed

The value to be formatted. It must be a factor e.g. 0.75 will result in 75%.

$decimals integer|null

The number of digits after the decimal point. If not given, the number of digits depends in the input value and is determined based on NumberFormatter::MIN_FRACTION_DIGITS and NumberFormatter::MAX_FRACTION_DIGITS, which can be configured using $numberFormatterOptions. If the PHP intl extension is not available, the default value is 0. If you want consistent behavior between environments where intl is available and not, you should explicitly specify a value here.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

                public function asPercent($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $normalizedValue = $this->normalizeNumericValue($value);
    if ($this->isNormalizedValueMispresented($value, $normalizedValue)) {
        return $this->asPercentStringFallback((string) $value, $decimals);
    }
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::PERCENT, $decimals, $options, $textOptions);
        if (($result = $f->format($normalizedValue)) === false) {
            throw new InvalidArgumentException('Formatting percent value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    if ($decimals === null) {
        $decimals = 0;
    }
    $normalizedValue *= 100;
    return number_format($normalizedValue, $decimals, $this->decimalSeparator, $this->thousandSeparator) . '%';
}

            
asPercentStringFallback() protected method (available since version 2.0.16)

Fallback for formatting value as a percent number with "%" sign.

Property $decimalSeparator will be used to represent the decimal point. The value is rounded automatically to the defined decimal digits.

protected string asPercentStringFallback ( $value, $decimals null )
$value string|integer|float

The value to be formatted.

$decimals integer|null

The number of digits after the decimal point. The default value is 0.

return string

The formatted result.

                protected function asPercentStringFallback($value, $decimals = null)
{
    if (empty($value)) {
        $value = 0;
    }
    if ($decimals === null) {
        $decimals = 0;
    }
    $value = $this->normalizeNumericStringValue((string) $value);
    $separatorPosition = strrpos($value, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($value, 0, $separatorPosition);
        $fractionalPart = str_pad(substr($value, $separatorPosition + 1), 2, '0');
        $integerPart .= substr($fractionalPart, 0, 2);
        $fractionalPart = substr($fractionalPart, 2);
        if ($fractionalPart === '') {
            $multipliedValue = $integerPart;
        } else {
            $multipliedValue = $integerPart . '.' . $fractionalPart;
        }
    } else {
        $multipliedValue = $value . '00';
    }
    return $this->asDecimalStringFallback($multipliedValue, $decimals) . '%';
}

            
asRaw() public method

Formats the value as is without any formatting.

This method simply returns back the parameter without any format. The only exception is a null value which will be formatted using $nullDisplay.

public string asRaw ( $value )
$value mixed

The value to be formatted.

return string

The formatted result.

                public function asRaw($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return $value;
}

            
asRelativeTime() public method

Formats the value as the time interval between a date and now in human readable form.

This method can be used in three different ways:

  1. Using a timestamp that is relative to now.
  2. Using a timestamp that is relative to the $referenceTime.
  3. Using a DateInterval object.
public string asRelativeTime ( $value, $referenceTime null )
$value integer|string|DateTime|DateTimeInterface|DateInterval|null

The value to be formatted. The following types of value are supported:

  • an integer representing a UNIX timestamp
  • a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given.
  • a PHP DateTime object
  • a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
$referenceTime integer|string|DateTime|DateTimeInterface|null

If specified the value is used as a reference time instead of now when $value is not a DateInterval object.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value can not be evaluated as a date value.

                public function asRelativeTime($value, $referenceTime = null)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    if ($value instanceof DateInterval) {
        $interval = $value;
    } else {
        $timestamp = $this->normalizeDatetimeValue($value);
        $timeZone = new DateTimeZone($this->timeZone);
        if ($referenceTime === null) {
            $dateNow = new DateTime('now', $timeZone);
        } else {
            $dateNow = $this->normalizeDatetimeValue($referenceTime);
            $dateNow->setTimezone($timeZone);
        }
        $dateThen = $timestamp->setTimezone($timeZone);
        $interval = $dateThen->diff($dateNow);
    }
    if ($interval->invert) {
        if ($interval->y >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a year} other{# years}}', ['delta' => $interval->y], $this->language);
        }
        if ($interval->m >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a month} other{# months}}', ['delta' => $interval->m], $this->language);
        }
        if ($interval->d >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a day} other{# days}}', ['delta' => $interval->d], $this->language);
        }
        if ($interval->h >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{an hour} other{# hours}}', ['delta' => $interval->h], $this->language);
        }
        if ($interval->i >= 1) {
            return Yii::t('yii', 'in {delta, plural, =1{a minute} other{# minutes}}', ['delta' => $interval->i], $this->language);
        }
        if ($interval->s == 0) {
            return Yii::t('yii', 'just now', [], $this->language);
        }
        return Yii::t('yii', 'in {delta, plural, =1{a second} other{# seconds}}', ['delta' => $interval->s], $this->language);
    }
    if ($interval->y >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a year} other{# years}} ago', ['delta' => $interval->y], $this->language);
    }
    if ($interval->m >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a month} other{# months}} ago', ['delta' => $interval->m], $this->language);
    }
    if ($interval->d >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a day} other{# days}} ago', ['delta' => $interval->d], $this->language);
    }
    if ($interval->h >= 1) {
        return Yii::t('yii', '{delta, plural, =1{an hour} other{# hours}} ago', ['delta' => $interval->h], $this->language);
    }
    if ($interval->i >= 1) {
        return Yii::t('yii', '{delta, plural, =1{a minute} other{# minutes}} ago', ['delta' => $interval->i], $this->language);
    }
    if ($interval->s == 0) {
        return Yii::t('yii', 'just now', [], $this->language);
    }
    return Yii::t('yii', '{delta, plural, =1{a second} other{# seconds}} ago', ['delta' => $interval->s], $this->language);
}

            
asScientific() public method

Formats the value as a scientific number.

public string asScientific ( $value, $decimals null, $options = [], $textOptions = [] )
$value mixed

The value to be formatted.

$decimals integer|null

The number of digits after the decimal point. If not given, the number of digits depends in the input value and is determined based on NumberFormatter::MIN_FRACTION_DIGITS and NumberFormatter::MAX_FRACTION_DIGITS, which can be configured using $numberFormatterOptions. If the PHP intl extension is not available, the default value depends on your PHP configuration. If you want consistent behavior between environments where intl is available and not, you should explicitly specify a value here.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

                public function asScientific($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $value = $this->normalizeNumericValue($value);
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::SCIENTIFIC, $decimals, $options, $textOptions);
        if (($result = $f->format($value)) === false) {
            throw new InvalidArgumentException('Formatting scientific number value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    if ($decimals !== null) {
        return sprintf("%.{$decimals}E", $value);
    }
    return sprintf('%.E', $value);
}

            
asShortLength() public method (available since version 2.0.13)

Formats the value as a length in human readable form for example 12 m.

This is the short form of asLength().

Check properties $baseUnits if you need to change unit of value as the multiplier of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.

See also asLength().

public string asShortLength ( $value, $decimals null, $options = [], $textOptions = [] )
$value float|integer

Value to be formatted.

$decimals integer|null

The number of digits after the decimal point.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

throws yii\base\InvalidConfigException

when INTL is not installed or does not contain required information.

                public function asShortLength($value, $decimals = null, $options = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_LENGTH, self::FORMAT_WIDTH_SHORT, $value, $decimals, $options, $textOptions);
}

            
asShortSize() public method

Formats the value in bytes as a size in human readable form for example 12 kB.

This is the short form of asSize().

If $sizeFormatBase is 1024, binary prefixes (e.g. kibibyte/KiB, mebibyte/MiB, ...) are used in the formatting result.

See also:

public string asShortSize ( $value, $decimals null, $options = [], $textOptions = [] )
$value string|integer|float|null

Value in bytes to be formatted.

$decimals integer|null

The number of digits after the decimal point.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

                public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions);
    if ($this->sizeFormatBase == 1024) {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} B', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} KiB', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} MiB', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} GiB', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} TiB', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} PiB', $params, $this->language);
        }
    } else {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} B', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} kB', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} MB', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} GB', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} TB', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} PB', $params, $this->language);
        }
    }
}

            
asShortWeight() public method (available since version 2.0.13)

Formats the value as a weight in human readable form for example 12 kg.

This is the short form of asWeight().

Check properties $baseUnits if you need to change unit of value as the multiplier of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.

public string asShortWeight ( $value, $decimals null, $options = [], $textOptions = [] )
$value float|integer

Value to be formatted.

$decimals integer|null

The number of digits after the decimal point.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

throws yii\base\InvalidConfigException

when INTL is not installed or does not contain required information.

                public function asShortWeight($value, $decimals = null, $options = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_WEIGHT, self::FORMAT_WIDTH_SHORT, $value, $decimals, $options, $textOptions);
}

            
asSize() public method

Formats the value in bytes as a size in human readable form, for example 12 kilobytes.

If $sizeFormatBase is 1024, binary prefixes (e.g. kibibyte/KiB, mebibyte/MiB, ...) are used in the formatting result.

See also:

public string asSize ( $value, $decimals null, $options = [], $textOptions = [] )
$value string|integer|float|null

Value in bytes to be formatted.

$decimals integer|null

The number of digits after the decimal point.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

                public function asSize($value, $decimals = null, $options = [], $textOptions = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions);
    if ($this->sizeFormatBase == 1024) {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}', $params, $this->language);
        }
    } else {
        switch ($position) {
            case 0:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{byte} other{bytes}}', $params, $this->language);
            case 1:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}', $params, $this->language);
            case 2:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{megabyte} other{megabytes}}', $params, $this->language);
            case 3:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}', $params, $this->language);
            case 4:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}', $params, $this->language);
            default:
                return Yii::t('yii', '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}', $params, $this->language);
        }
    }
}

            
asSpellout() public method

Formats the value as a number spellout.

This function requires the PHP intl extension to be installed.

This formatter does not work well with very big numbers.

public string asSpellout ( $value )
$value mixed

The value to be formatted

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

throws yii\base\InvalidConfigException

when the PHP intl extension is not available.

                public function asSpellout($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $value = $this->normalizeNumericValue($value);
    if ($this->_intlLoaded) {
        $f = $this->createNumberFormatter(NumberFormatter::SPELLOUT);
        if (($result = $f->format($value)) === false) {
            throw new InvalidArgumentException('Formatting number as spellout failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
        }
        return $result;
    }
    throw new InvalidConfigException('Format as Spellout is only supported when PHP intl extension is installed.');
}

            
asText() public method

Formats the value as an HTML-encoded plain text.

public string asText ( $value )
$value string|null

The value to be formatted.

return string

The formatted result.

                public function asText($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    return Html::encode($value);
}

            
asTime() public method

Formats the value as a time.

See also $timeFormat.

public string asTime ( $value, $format null )
$value integer|string|DateTime|DateTimeInterface|null

The value to be formatted. The following types of value are supported:

  • an integer representing a UNIX timestamp. A UNIX timestamp is always in UTC by its definition.
  • a string that can be parsed to create a DateTime object. The timestamp is assumed to be in $defaultTimeZone unless a time zone is explicitly given.
  • a PHP DateTime object. You may set the time zone for the DateTime object to specify the source time zone.

The formatter will convert date values according to $timeZone before formatting it. If no timezone conversion should be performed, you need to set $defaultTimeZone and $timeZone to the same value.

$format string|null

The format used to convert the value into a date string. If null, $timeFormat will be used.

This can be "short", "medium", "long", or "full", which represents a preset format of different lengths. It can also be a custom format as specified in the ICU manual.

Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP date()-function.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value can not be evaluated as a date value.

throws yii\base\InvalidConfigException

if the date format is invalid.

                public function asTime($value, $format = null)
{
    if ($format === null) {
        $format = $this->timeFormat;
    }
    return $this->formatDateTimeValue($value, $format, 'time');
}

            
asTimestamp() public method

Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).

public string asTimestamp ( $value )
$value integer|string|DateTime|DateTimeInterface|null

The value to be formatted. The following types of value are supported:

return string

The formatted result.

                public function asTimestamp($value)
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $timestamp = $this->normalizeDatetimeValue($value);
    return number_format($timestamp->format('U'), 0, '.', '');
}

            
asUrl() public method

Formats the value as a hyperlink.

public string asUrl ( $value, $options = [] )
$value mixed

The value to be formatted.

$options array

The tag options in terms of name-value pairs. See yii\helpers\Html::a(). Since 2.0.43 there is a special option available scheme - if set it won't be passed to yii\helpers\Html::a() but it will control the URL protocol part of the link by normalizing URL and ensuring that it uses specified scheme. See yii\helpers\Url::ensureScheme(). If scheme is not set the original behavior is preserved which is to add "http://" prefix when "://" string is not found in the $value.

return string

The formatted result.

                public function asUrl($value, $options = [])
{
    if ($value === null) {
        return $this->nullDisplay;
    }
    $url = $value;
    $scheme = ArrayHelper::remove($options, 'scheme');
    if ($scheme === null) {
        if (strpos($url, '://') === false) {
            $url = 'http://' . $url;
        }
    } else {
        $url = Url::ensureScheme($url, $scheme);
    }
    return Html::a(Html::encode($value), $url, $options);
}

            
asWeight() public method (available since version 2.0.13)

Formats the value as a weight in human readable form for example 12 kilograms.

Check properties $baseUnits if you need to change unit of value as the multiplier of the smallest unit and $systemOfUnits to switch between UNIT_SYSTEM_METRIC or UNIT_SYSTEM_IMPERIAL.

public string asWeight ( $value, $decimals null, $options = [], $textOptions = [] )
$value float|integer

Value to be formatted.

$decimals integer|null

The number of digits after the decimal point.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return string

The formatted result.

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

throws yii\base\InvalidConfigException

when INTL is not installed or does not contain required information.

                public function asWeight($value, $decimals = null, $options = [], $textOptions = [])
{
    return $this->formatUnit(self::UNIT_WEIGHT, self::FORMAT_WIDTH_LONG, $value, $decimals, $options, $textOptions);
}

            
attachBehavior() public method

Defined in: yii\base\Component::attachBehavior()

Attaches a behavior to this component.

This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.

See also detachBehavior().

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

The name of the behavior.

$behavior string|array|yii\base\Behavior

The behavior configuration. This can be one of the following:

return yii\base\Behavior

The behavior object

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() public method

Defined in: yii\base\Component::attachBehaviors()

Attaches a list of behaviors to the component.

Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.

See also attachBehavior().

public void attachBehaviors ( $behaviors )
$behaviors array

List of behaviors to be attached to the component

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
behaviors() public method

Defined in: yii\base\Component::behaviors()

Returns a list of behaviors that this component should behave as.

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

public array behaviors ( )
return array

The behavior configurations.

                public function behaviors()
{
    return [];
}

            
canGetProperty() public method

Defined in: yii\base\Component::canGetProperty()

Returns a value indicating whether a property can be read.

A property can be read if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
canSetProperty() public method

Defined in: yii\base\Component::canSetProperty()

Returns a value indicating whether a property can be set.

A property can be written if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
createNumberFormatter() protected method

Creates a number formatter based on the given type and format.

You may override this method to create a number formatter based on patterns.

protected NumberFormatter createNumberFormatter ( $style, $decimals null, $options = [], $textOptions = [] )
$style integer

The type of the number formatter. Values: NumberFormatter::DECIMAL, ::CURRENCY, ::PERCENT, ::SCIENTIFIC, ::SPELLOUT, ::ORDINAL ::DURATION, ::PATTERN_RULEBASED, ::DEFAULT_STYLE, ::IGNORE

$decimals integer|null

The number of digits after the decimal point.

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return NumberFormatter

The created formatter instance

                protected function createNumberFormatter($style, $decimals = null, $options = [], $textOptions = [])
{
    $formatter = new NumberFormatter($this->locale, $style);
    // set text attributes
    foreach ($this->numberFormatterTextOptions as $attribute => $value) {
        $this->setFormatterTextAttribute($formatter, $attribute, $value, 'numberFormatterTextOptions', 'numberFormatterOptions');
    }
    foreach ($textOptions as $attribute => $value) {
        $this->setFormatterTextAttribute($formatter, $attribute, $value, '$textOptions', '$options');
    }
    // set attributes
    foreach ($this->numberFormatterOptions as $attribute => $value) {
        $this->setFormatterIntAttribute($formatter, $attribute, $value, 'numberFormatterOptions', 'numberFormatterTextOptions');
    }
    foreach ($options as $attribute => $value) {
        $this->setFormatterIntAttribute($formatter, $attribute, $value, '$options', '$textOptions');
    }
    if ($decimals !== null) {
        $formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
        $formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimals);
    }
    // set symbols
    if ($this->decimalSeparator !== null) {
        $formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimalSeparator);
    }
    if ($this->currencyDecimalSeparator !== null) {
        $formatter->setSymbol(NumberFormatter::MONETARY_SEPARATOR_SYMBOL, $this->currencyDecimalSeparator);
    }
    if ($this->thousandSeparator !== null) {
        $formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
        $formatter->setSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, $this->thousandSeparator);
    }
    foreach ($this->numberFormatterSymbols as $symbol => $value) {
        $this->setFormatterSymbol($formatter, $symbol, $value, 'numberFormatterSymbols');
    }
    return $formatter;
}

            
detachBehavior() public method

Defined in: yii\base\Component::detachBehavior()

Detaches a behavior from the component.

The behavior's yii\base\Behavior::detach() method will be invoked.

public yii\base\Behavior|null detachBehavior ( $name )
$name string

The behavior's name.

return yii\base\Behavior|null

The detached behavior. Null if the behavior does not exist.

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() public method

Defined in: yii\base\Component::detachBehaviors()

Detaches all behaviors from the component.

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() public method

Defined in: yii\base\Component::ensureBehaviors()

Makes sure that the behaviors declared in behaviors() are attached to this component.

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
format() public method

Formats the value based on the given format type.

This method will call one of the "as" methods available in this class to do the formatting. For type "xyz", the method "asXyz" will be used. For example, if the format is "html", then asHtml() will be used. Format names are case insensitive.

public string format ( $value, $format )
$value mixed

The value to be formatted.

$format string|array|Closure

The format of the value, e.g., "html", "text" or an anonymous function returning the formatted value.

To specify additional parameters of the formatting method, you may use an array. The first element of the array specifies the format name, while the rest of the elements will be used as the parameters to the formatting method. For example, a format of ['date', 'Y-m-d'] will cause the invocation of asDate($value, 'Y-m-d').

The anonymous function signature should be: function($value, $formatter), where $value is the value that should be formatted and $formatter is an instance of the Formatter class, which can be used to call other formatting functions. The possibility to use an anonymous function is available since version 2.0.13.

return string

The formatting result.

throws yii\base\InvalidArgumentException

if the format type is not supported by this class.

                public function format($value, $format)
{
    if ($format instanceof Closure) {
        return $format($value, $this);
    }
    if (is_array($format)) {
        if (!isset($format[0])) {
            throw new InvalidArgumentException('The $format array must contain at least one element.');
        }
        $f = $format[0];
        $format[0] = $value;
        $params = $format;
        $format = $f;
    } else {
        $params = [$value];
    }
    $method = 'as' . $format;
    if ($this->hasMethod($method)) {
        return call_user_func_array([$this, $method], $params);
    }
    throw new InvalidArgumentException("Unknown format type: $format");
}

            
formatNumber() protected method (available since version 2.0.32)

Given the value in bytes formats number part of the human readable form.

protected array formatNumber ( $value, $decimals, $maxPosition, $formatBase, $options, $textOptions )
$value string|integer|float

Value in bytes to be formatted.

$decimals integer|null

The number of digits after the decimal point

$maxPosition integer

Maximum internal position of size unit, ignored if $formatBase is an array

$formatBase array|integer

The base at which each next unit is calculated, either 1000 or 1024, or an array

$options array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterOptions.

$textOptions array

Optional configuration for the number formatter. This parameter will be merged with $numberFormatterTextOptions.

return array

[parameters for Yii::t containing formatted number, internal position of size unit]

throws yii\base\InvalidArgumentException

if the input value is not numeric or the formatting failed.

                protected function formatNumber($value, $decimals, $maxPosition, $formatBase, $options, $textOptions)
{
    $value = $this->normalizeNumericValue($value);
    $position = 0;
    if (is_array($formatBase)) {
        $maxPosition = count($formatBase) - 1;
    }
    do {
        if (is_array($formatBase)) {
            if (!isset($formatBase[$position + 1])) {
                break;
            }
            if (abs($value) < $formatBase[$position + 1]) {
                break;
            }
        } else {
            if (abs($value) < $formatBase) {
                break;
            }
            $value /= $formatBase;
        }
        $position++;
    } while ($position < $maxPosition + 1);
    if (is_array($formatBase) && $position !== 0) {
        $value /= $formatBase[$position];
    }
    // no decimals for smallest unit
    if ($position === 0) {
        $decimals = 0;
    } elseif ($decimals !== null) {
        $value = round($value, $decimals);
    }
    // disable grouping for edge cases like 1023 to get 1023 B instead of 1,023 B
    $oldThousandSeparator = $this->thousandSeparator;
    $this->thousandSeparator = '';
    if ($this->_intlLoaded && !isset($options[NumberFormatter::GROUPING_USED])) {
        $options[NumberFormatter::GROUPING_USED] = 0;
    }
    // format the size value
    $params = [
        // this is the unformatted number used for the plural rule
        // abs() to make sure the plural rules work correctly on negative numbers, intl does not cover this
        // https://english.stackexchange.com/questions/9735/is-1-followed-by-a-singular-or-plural-noun
        'n' => abs($value),
        // this is the formatted number used for display
        'nFormatted' => $this->asDecimal($value, $decimals, $options, $textOptions),
    ];
    $this->thousandSeparator = $oldThousandSeparator;
    return [$params, $position];
}

            
getBehavior() public method

Defined in: yii\base\Component::getBehavior()

Returns the named behavior object.

public yii\base\Behavior|null getBehavior ( $name )
$name string

The behavior name

return yii\base\Behavior|null

The behavior object, or null if the behavior does not exist

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() public method

Defined in: yii\base\Component::getBehaviors()

Returns all behaviors attached to this component.

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

List of behaviors attached to this component

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
hasEventHandlers() public method

Defined in: yii\base\Component::hasEventHandlers()

Returns a value indicating whether there is any handler attached to the named event.

public boolean hasEventHandlers ( $name )
$name string

The event name

return boolean

Whether there is any handler attached to the event.

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() public method

Defined in: yii\base\Component::hasMethod()

Returns a value indicating whether a method is defined.

A method is defined if:

  • the class has a method with the specified name
  • an attached behavior has a method with the given name (when $checkBehaviors is true).
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

The property name

$checkBehaviors boolean

Whether to treat behaviors' methods as methods of this component

return boolean

Whether the method is defined

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() public method

Defined in: yii\base\Component::hasProperty()

Returns a value indicating whether a property is defined for this component.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a property of the given name (when $checkBehaviors is true).

See also:

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
init() public method

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )

                public function init()
{
    if ($this->timeZone === null) {
        $this->timeZone = Yii::$app->timeZone;
    }
    if ($this->locale === null) {
        $this->locale = Yii::$app->language;
    }
    if ($this->language === null) {
        $this->language = strtok($this->locale, '@');
    }
    if ($this->booleanFormat === null) {
        $this->booleanFormat = [Yii::t('yii', 'No', [], $this->language), Yii::t('yii', 'Yes', [], $this->language)];
    }
    if ($this->nullDisplay === null) {
        $this->nullDisplay = '<span class="not-set">' . Yii::t('yii', '(not set)', [], $this->language) . '</span>';
    }
    $this->_intlLoaded = extension_loaded('intl');
    if (!$this->_intlLoaded) {
        if ($this->decimalSeparator === null) {
            $this->decimalSeparator = '.';
        }
        if ($this->thousandSeparator === null) {
            $this->thousandSeparator = ',';
        }
    }
}

            
isNormalizedValueMispresented() protected method (available since version 2.0.16)

Checks if string representations of given value and its normalized version are different.

protected boolean isNormalizedValueMispresented ( $value, $normalizedValue )
$value string|float|integer
$normalizedValue float|integer

                protected function isNormalizedValueMispresented($value, $normalizedValue)
{
    if (empty($value)) {
        $value = 0;
    }
    return (string) $normalizedValue !== $this->normalizeNumericStringValue((string) $value);
}

            
normalizeDatetimeValue() protected method

Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.

protected DateTime|array normalizeDatetimeValue ( $value, $checkDateTimeInfo false )
$value integer|string|DateTime|DateTimeInterface|null

The datetime value to be normalized. The following types of value are supported:

$checkDateTimeInfo boolean

Whether to also check if the date/time value has some time and date information attached. Defaults to false. If true, the method will then return an array with the first element being the normalized timestamp, the second a boolean indicating whether the timestamp has time information and third a boolean indicating whether the timestamp has date information. This parameter is available since version 2.0.1.

return DateTime|array

The normalized datetime value Since version 2.0.1 this may also return an array if $checkDateTimeInfo is true. The first element of the array is the normalized timestamp and the second is a boolean indicating whether the timestamp has time information or it is just a date value. Since version 2.0.12 the array has third boolean element indicating whether the timestamp has date information or it is just a time value.

throws yii\base\InvalidArgumentException

if the input value can not be evaluated as a date value.

                protected function normalizeDatetimeValue($value, $checkDateTimeInfo = false)
{
    // checking for DateTime and DateTimeInterface is not redundant, DateTimeInterface is only in PHP>5.5
    if ($value === null || $value instanceof DateTime || $value instanceof DateTimeInterface) {
        // skip any processing
        return $checkDateTimeInfo ? [$value, true, true] : $value;
    }
    if (empty($value)) {
        $value = 0;
    }
    try {
        if (is_numeric($value)) { // process as unix timestamp, which is always in UTC
            $timestamp = new DateTime('@' . (int) $value, new DateTimeZone('UTC'));
            return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp;
        }
        if (
            ($timestamp = DateTime::createFromFormat(
                'Y-m-d|',
                $value,
                new DateTimeZone($this->defaultTimeZone))
            ) !== false
        ) { // try Y-m-d format (support invalid dates like 2012-13-01)
            return $checkDateTimeInfo ? [$timestamp, false, true] : $timestamp;
        }
        if (
            ($timestamp = DateTime::createFromFormat(
                'Y-m-d H:i:s',
                $value,
                new DateTimeZone($this->defaultTimeZone))
            ) !== false
        ) { // try Y-m-d H:i:s format (support invalid dates like 2012-13-01 12:63:12)
            return $checkDateTimeInfo ? [$timestamp, true, true] : $timestamp;
        }
        // finally try to create a DateTime object with the value
        if ($checkDateTimeInfo) {
            $timestamp = new DateTime($value, new DateTimeZone($this->defaultTimeZone));
            $info = date_parse($value);
            return [
                $timestamp,
                !($info['hour'] === false && $info['minute'] === false && $info['second'] === false),
                !($info['year'] === false && $info['month'] === false && $info['day'] === false && empty($info['zone'])),
            ];
        }
        return new DateTime($value, new DateTimeZone($this->defaultTimeZone));
    } catch (\Exception $e) {
        throw new InvalidArgumentException("'$value' is not a valid date time value: " . $e->getMessage()
            . "\n" . print_r(DateTime::getLastErrors(), true), $e->getCode(), $e);
    }
}

            
normalizeNumericStringValue() protected method (available since version 2.0.16)

Normalizes a numeric string value.

protected string normalizeNumericStringValue ( $value )
$value string
return string

The normalized number value as a string

                protected function normalizeNumericStringValue($value)
{
    $powerPosition = strrpos($value, 'E');
    if ($powerPosition !== false) {
        $valuePart = substr($value, 0, $powerPosition);
        $powerPart = substr($value, $powerPosition + 1);
    } else {
        $powerPart = null;
        $valuePart = $value;
    }
    $separatorPosition = strrpos($valuePart, '.');
    if ($separatorPosition !== false) {
        $integerPart = substr($valuePart, 0, $separatorPosition);
        $fractionalPart = substr($valuePart, $separatorPosition + 1);
    } else {
        $integerPart = $valuePart;
        $fractionalPart = null;
    }
    // truncate insignificant zeros, keep minus
    $integerPart = preg_replace('/^\+?(-?)0*(\d+)$/', '$1$2', $integerPart);
    // for zeros only leave one zero, keep minus
    $integerPart = preg_replace('/^\+?(-?)0*$/', '${1}0', $integerPart);
    if ($fractionalPart !== null) {
        // truncate insignificant zeros
        $fractionalPart = rtrim($fractionalPart, '0');
        if (empty($fractionalPart)) {
            $fractionalPart = $powerPart !== null ? '0' : null;
        }
    }
    $normalizedValue = $integerPart;
    if ($fractionalPart !== null) {
        $normalizedValue .= '.' . $fractionalPart;
    } elseif ($normalizedValue === '-0') {
        $normalizedValue = '0';
    }
    if ($powerPart !== null) {
        $normalizedValue .= 'E' . $powerPart;
    }
    return $normalizedValue;
}

            
normalizeNumericValue() protected method

Normalizes a numeric input value.

  • everything empty will result in 0
  • a numeric string will be casted to float
  • everything else will be returned if it is numeric, otherwise an exception is thrown.
protected float|integer normalizeNumericValue ( $value )
$value mixed

The input value

return float|integer

The normalized number value

throws yii\base\InvalidArgumentException

if the input value is not numeric.

                protected function normalizeNumericValue($value)
{
    if (empty($value)) {
        return 0;
    }
    if (is_string($value) && is_numeric($value)) {
        $value = (float) $value;
    }
    if (!is_numeric($value)) {
        throw new InvalidArgumentException("'$value' is not a numeric value.");
    }
    return $value;
}

            
off() public method

Defined in: yii\base\Component::off()

Detaches an existing event handler from this component.

This method is the opposite of on().

Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.

See also on().

public boolean off ( $name, $handler null )
$name string

Event name

$handler callable|null

The event handler to be removed. If it is null, all handlers attached to the named event will be removed.

return boolean

If a handler is found and detached

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
on() public method

Defined in: yii\base\Component::on()

Attaches an event handler to an event.

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

The event handler must be defined with the following signature,

function ($event)

where $event is an yii\base\Event object which includes parameters associated with the event.

Since 2.0.14 you can specify event name as a wildcard pattern:

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

See also off().

public void on ( $name, $handler, $data null, $append true )
$name string

The event name

$handler callable

The event handler

$data mixed

The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data.

$append boolean

Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
trigger() public method

Defined in: yii\base\Component::trigger()

Triggers an event.

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

public void trigger ( $name, yii\base\Event $event null )
$name string

The event name

$event yii\base\Event|null

The event instance. If not set, a default yii\base\Event object will be created.

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}