HumHub Documentation (unofficial)

Formatter extends Formatter
in package

Formatter provides a set of commonly used data formatting methods.

Tags
inheritdoc

Table of Contents

Constants

FORMAT_WIDTH_LONG  = 'long'
FORMAT_WIDTH_SHORT  = 'short'
UNIT_LENGTH  = 'length'
UNIT_SYSTEM_IMPERIAL  = 'imperial'
UNIT_SYSTEM_METRIC  = 'metric'
UNIT_WEIGHT  = 'mass'

Properties

$baseUnits  : array<string|int, mixed>
$behaviors  : array<string|int, Behavior>
$booleanFormat  : array<string|int, mixed>
$calendar  : IntlCalendar|int|null
$currencyCode  : string|null
$currencyDecimalSeparator  : string|null
$dateFormat  : string
$dateInputFormat  : string
$datetimeFormat  : string
$decimalSeparator  : string|null
$defaultTimeZone  : string
$language  : string|null
$locale  : string|null
$measureUnits  : array<string|int, mixed>
$nullDisplay  : string|null
$numberFormatterOptions  : array<string|int, mixed>
$numberFormatterSymbols  : array<string|int, mixed>
$numberFormatterTextOptions  : array<string|int, mixed>
$sizeFormatBase  : int
$systemOfUnits  : string
$thousandSeparator  : string|null
$timeFormat  : string
$timeZone  : string|null
$_behaviors  : array<string|int, Behavior>|null
$_dateFormats  : array<string|int, mixed>
$_events  : array<string|int, mixed>
$_eventWildcards  : array<string|int, mixed>
$_intlLoaded  : bool
$_resourceBundle  : ResourceBundle
$_unitMessages  : array<string|int, mixed>

Methods

__call()  : mixed
Calls the named method which is not a class method.
__clone()  : mixed
This method is called after the object is created by cloning an existing one.
__construct()  : mixed
Constructor.
__get()  : mixed
Returns the value of a component property.
__isset()  : bool
Checks if a property is set, i.e. defined and not null.
__set()  : mixed
Sets the value of a component property.
__unset()  : mixed
Sets a component property to be null.
asBoolean()  : string
Formats the value as a boolean.
asCurrency()  : string
Formats the value as a currency number.
asDate()  : string
Formats the value as a date.
asDatetime()  : string
Formats the value as a datetime.
asDecimal()  : string
Formats the value as a decimal number.
asDuration()  : string
Represents the value as duration in human readable format.
asEmail()  : string
Formats the value as a mailto link.
asHtml()  : string
Formats the value as HTML text.
asImage()  : string
Formats the value as an image tag.
asInteger()  : string
Formats the value as an integer number by removing any decimal digits without rounding.
asLength()  : string
Formats the value as a length in human readable form for example `12 meters`.
asNtext()  : string
Formats the value as an HTML-encoded plain text with newlines converted into breaks.
asOrdinal()  : string
Formats the value as a ordinal value of a number.
asParagraphs()  : string
Formats the value as HTML-encoded text paragraphs.
asPercent()  : string
Formats the value as a percent number with "%" sign.
asRaw()  : string
Formats the value as is without any formatting.
asRelativeTime()  : string
Formats the value as the time interval between a date and now in human readable form.
asScientific()  : string
Formats the value as a scientific number.
asShortInteger()  : string
Formats the value as short integer number by removing any decimal and thousand digits without rounding.
asShortLength()  : string
Formats the value as a length in human readable form for example `12 m`.
asShortSize()  : string
Formats the value in bytes as a size in human readable form for example `12 kB`.
asShortWeight()  : string
Formats the value as a weight in human readable form for example `12 kg`.
asSize()  : string
Formats the value in bytes as a size in human readable form, for example `12 kilobytes`.
asSpellout()  : string
Formats the value as a number spellout.
asText()  : string
Formats the value as an HTML-encoded plain text.
asTime()  : string
Formats the value as a time.
asTimestamp()  : string
Formats a date, time or datetime in a float number as UNIX timestamp (seconds since 01-01-1970).
asUrl()  : string
Formats the value as a hyperlink.
asWeight()  : string
Formats the value as a weight in human readable form for example `12 kilograms`.
attachBehavior()  : Behavior
Attaches a behavior to this component.
attachBehaviors()  : mixed
Attaches a list of behaviors to the component.
behaviors()  : array<string|int, mixed>
Returns a list of behaviors that this component should behave as.
canGetProperty()  : bool
Returns a value indicating whether a property can be read.
canSetProperty()  : bool
Returns a value indicating whether a property can be set.
className()  : string
Returns the fully qualified name of this class.
detachBehavior()  : Behavior|null
Detaches a behavior from the component.
detachBehaviors()  : mixed
Detaches all behaviors from the component.
ensureBehaviors()  : mixed
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
format()  : string
Formats the value based on the given format type.
getBehavior()  : Behavior|null
Returns the named behavior object.
getBehaviors()  : array<string|int, Behavior>
Returns all behaviors attached to this component.
getDateTimePattern()  : null|string
Returns the date pattern for the given $locale and $dateType, $timeType.
hasEventHandlers()  : bool
Returns a value indicating whether there is any handler attached to the named event.
hasMethod()  : bool
Returns a value indicating whether a method is defined.
hasProperty()  : bool
Returns a value indicating whether a property is defined for this component.
init()  : mixed
Initializes the object.
isShowMeridiem()  : bool
Checks if the time pattern of a given $locale contains a meridiem (AM/PM).
off()  : bool
Detaches an existing event handler from this component.
on()  : mixed
Attaches an event handler to an event.
trigger()  : mixed
Triggers an event.
asCurrencyStringFallback()  : string
Fallback for formatting value as a currency number.
asDecimalStringFallback()  : string
Fallback for formatting value as a decimal number.
asIntegerStringFallback()  : string
Fallback for formatting value as an integer number by removing any decimal digits without rounding.
asPercentStringFallback()  : string
Fallback for formatting value as a percent number with "%" sign.
createNumberFormatter()  : NumberFormatter
Creates a number formatter based on the given type and format.
formatNumber()  : array<string|int, mixed>
Given the value in bytes formats number part of the human readable form.
isNormalizedValueMispresented()  : bool
Checks if string representations of given value and its normalized version are different.
normalizeDatetimeValue()  : DateTime|array<string|int, mixed>
Normalizes the given datetime value as a DateTime object that can be taken by various date/time formatting methods.
normalizeNumericStringValue()  : string
Normalizes a numeric string value.
normalizeNumericValue()  : float|int
Normalizes a numeric input value.
attachBehaviorInternal()  : Behavior
Attaches a behavior to this component.
formatDateTimeValue()  : string
formatUnit()  : string
getUnitMessage()  : string
setFormatterIntAttribute()  : mixed
setFormatterSymbol()  : mixed
setFormatterTextAttribute()  : mixed

Constants

FORMAT_WIDTH_LONG

public mixed FORMAT_WIDTH_LONG = 'long'
Tags
since
2.0.13

FORMAT_WIDTH_SHORT

public mixed FORMAT_WIDTH_SHORT = 'short'
Tags
since
2.0.13

UNIT_LENGTH

public mixed UNIT_LENGTH = 'length'
Tags
since
2.0.13

UNIT_SYSTEM_IMPERIAL

public mixed UNIT_SYSTEM_IMPERIAL = 'imperial'
Tags
since
2.0.13

UNIT_SYSTEM_METRIC

public mixed UNIT_SYSTEM_METRIC = 'metric'
Tags
since
2.0.13

UNIT_WEIGHT

public mixed UNIT_WEIGHT = 'mass'
Tags
since
2.0.13

Properties

$baseUnits

public array<string|int, mixed> $baseUnits = [self::UNIT_LENGTH => [ self::UNIT_SYSTEM_IMPERIAL => 12, // 1 feet = 12 inches self::UNIT_SYSTEM_METRIC => 1000, ], self::UNIT_WEIGHT => [ self::UNIT_SYSTEM_IMPERIAL => 7000, // 1 pound = 7000 grains self::UNIT_SYSTEM_METRIC => 1000, ]]

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

Tags
since
2.0.13

$behaviors read-only

public array<string|int, Behavior> $behaviors

List of behaviors attached to this component.

$booleanFormat

public array<string|int, mixed> $booleanFormat

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]].

$calendar

public IntlCalendar|int|null $calendar

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.

Tags
see
https://www.php.net/manual/en/intldateformatter.create.php
see
https://www.php.net/manual/en/class.intldateformatter.php#intl.intldateformatter-constants.calendartypes
see
https://www.php.net/manual/en/class.intlcalendar.php
since
2.0.7

$currencyCode

public string|null $currencyCode

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.

$currencyDecimalSeparator

public string|null $currencyDecimalSeparator

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.

Tags
since
2.0.35

$dateFormat

public string $dateFormat = 'medium'

the default format string to be used to format a [[asDate()|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

$dateInputFormat

public string $dateInputFormat = 'short'

the default format string to be used to format a input field [[asDate()|date]]. This mostly used in forms (DatePicker).

Tags
see
dateFormat

$datetimeFormat

public string $datetimeFormat = 'medium'

the default format string to be used to format a [[asDatetime()|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

$decimalSeparator

public string|null $decimalSeparator

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 string $defaultTimeZone = 'UTC'

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.

Tags
since
2.0.1

$language

public string|null $language

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).

Tags
since
2.0.28

$locale

public string|null $locale

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.

$measureUnits

public array<string|int, mixed> $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]]]

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
]
Tags
see
asLength
see
asWeight
since
2.0.13

$nullDisplay

public string|null $nullDisplay

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]].

$numberFormatterOptions

public array<string|int, mixed> $numberFormatterOptions = []

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 array<string|int, mixed> $numberFormatterSymbols = []

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 => '₽',
]
Tags
since
2.0.4

$numberFormatterTextOptions

public array<string|int, mixed> $numberFormatterTextOptions = []

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 int $sizeFormatBase = 1000

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

Tags
inheritdoc

$systemOfUnits

public string $systemOfUnits = self::UNIT_SYSTEM_METRIC

default system of measure units. Defaults to [[UNIT_SYSTEM_METRIC]]. Possible values:

  • [[UNIT_SYSTEM_METRIC]]
  • [[UNIT_SYSTEM_IMPERIAL]]
Tags
see
asLength
see
asWeight
since
2.0.13

$thousandSeparator

public string|null $thousandSeparator

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 string $timeFormat = 'medium'

the default format string to be used to format a [[asTime()|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

$timeZone

public string|null $timeZone

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.

$_behaviors

private array<string|int, Behavior>|null $_behaviors

the attached behaviors (behavior name => behavior). This is null when not initialized.

$_dateFormats

private array<string|int, mixed> $_dateFormats = [ 'short' => 3, // IntlDateFormatter::SHORT, 'medium' => 2, // IntlDateFormatter::MEDIUM, 'long' => 1, // IntlDateFormatter::LONG, 'full' => 0, ]

map of short format names to IntlDateFormatter constant values.

$_events

private array<string|int, mixed> $_events = []

the attached event handlers (event name => handlers)

$_eventWildcards

private array<string|int, mixed> $_eventWildcards = []

the event handlers attached for wildcard patterns (event name wildcard => handlers)

Tags
since
2.0.14

$_resourceBundle

private ResourceBundle $_resourceBundle

cached ResourceBundle object used to read unit translations

$_unitMessages

private array<string|int, mixed> $_unitMessages = []

cached unit translation patterns

Methods

__call()

Calls the named method which is not a class method.

public __call(string $name, array<string|int, mixed> $params) : mixed

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.

Parameters
$name : string

the method name

$params : array<string|int, mixed>

method parameters

Tags
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__clone()

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

public __clone() : mixed

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

__construct()

Constructor.

public __construct([array<string|int, mixed> $config = [] ]) : mixed

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.
Parameters
$config : array<string|int, mixed> = []

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

__get()

Returns the value of a component property.

public __get(string $name) : mixed

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;.

Parameters
$name : string

the property name

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is write-only.

see
__set()
Return values
mixed

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

__isset()

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

public __isset(string $name) : bool

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).

Parameters
$name : string

the property name or the event name

Tags
see
https://www.php.net/manual/en/function.isset.php
Return values
bool

whether the named property is set

__set()

Sets the value of a component property.

public __set(string $name, mixed $value) : mixed

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;.

Parameters
$name : string

the property name or the event name

$value : mixed

the property value

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is read-only.

see
__get()

__unset()

Sets a component property to be null.

public __unset(string $name) : mixed

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).

Parameters
$name : string

the property name

Tags
throws
InvalidCallException

if the property is read only.

see
https://www.php.net/manual/en/function.unset.php

asBoolean()

Formats the value as a boolean.

public asBoolean(mixed $value) : string
Parameters
$value : mixed

the value to be formatted.

Tags
see
booleanFormat
Return values
string

the formatted result.

asCurrency()

Formats the value as a currency number.

public asCurrency(mixed $value[, string|null $currency = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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.

Parameters
$value : mixed

the value to be formatted.

$currency : string|null = null

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

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

if no currency is given and [[currencyCode]] is not defined.

Return values
string

the formatted result.

asDate()

Formats the value as a date.

public asDate(int|string|DateTime|DateTimeInterface|null $value[, string|null $format = null ]) : string
Parameters
$value : int|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 = 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.

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

if the date format is invalid.

see
dateFormat
Return values
string

the formatted result.

asDatetime()

Formats the value as a datetime.

public asDatetime(int|string|DateTime|DateTimeInterface|null $value[, string|null $format = null ]) : string
Parameters
$value : int|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 = 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.

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

if the date format is invalid.

see
datetimeFormat
Return values
string

the formatted result.

asDecimal()

Formats the value as a decimal number.

public asDecimal(mixed $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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.

Parameters
$value : mixed

the value to be formatted.

$decimals : int|null = 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<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

see
decimalSeparator
see
thousandSeparator
Return values
string

the formatted result.

asDuration()

Represents the value as duration in human readable format.

public asDuration(DateInterval|string|int|null $value[, string $implodeString = ', ' ][, string $negativeSign = '-' ]) : string
Parameters
$value : DateInterval|string|int|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 -.

Tags
since
2.0.7
Return values
string

the formatted duration.

asEmail()

Formats the value as a mailto link.

public asEmail(string|null $value[, array<string|int, mixed> $options = [] ]) : string
Parameters
$value : string|null

the value to be formatted.

$options : array<string|int, mixed> = []

the tag options in terms of name-value pairs. See [[Html::mailto()]].

Return values
string

the formatted result.

asHtml()

Formats the value as HTML text.

public asHtml(string|null $value[, array<string|int, mixed>|null $config = null ]) : string

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

Parameters
$value : string|null

the value to be formatted.

$config : array<string|int, mixed>|null = null

the configuration for the HTMLPurifier class.

Return values
string

the formatted result.

asImage()

Formats the value as an image tag.

public asImage(mixed $value[, array<string|int, mixed> $options = [] ]) : string
Parameters
$value : mixed

the value to be formatted.

$options : array<string|int, mixed> = []

the tag options in terms of name-value pairs. See [[Html::img()]].

Return values
string

the formatted result.

asInteger()

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

public asInteger(mixed $value[, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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.

Parameters
$value : mixed

the value to be formatted.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

Return values
string

the formatted result.

asLength()

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

public asLength(float|int $value[, int|null $decimals = null ][, array<string|int, mixed> $numberOptions = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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]].

Parameters
$value : float|int

value to be formatted.

$decimals : int|null = null

the number of digits after the decimal point.

$numberOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

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

see
asLength
since
2.0.13
author

John Was janek.jan@gmail.com

Return values
string

the formatted result.

asNtext()

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

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

the value to be formatted.

Return values
string

the formatted result.

asOrdinal()

Formats the value as a ordinal value of a number.

public asOrdinal(mixed $value) : string

This function requires the PHP intl extension to be installed.

This formatter does not work well with very big numbers.

Parameters
$value : mixed

the value to be formatted

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

when the PHP intl extension is not available.

Return values
string

the formatted result.

asParagraphs()

Formats the value as HTML-encoded text paragraphs.

public asParagraphs(string|null $value) : string

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

Parameters
$value : string|null

the value to be formatted.

Return values
string

the formatted result.

asPercent()

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

public asPercent(mixed $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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.

Parameters
$value : mixed

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

$decimals : int|null = 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<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

Return values
string

the formatted result.

asRaw()

Formats the value as is without any formatting.

public asRaw(mixed $value) : string

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

Parameters
$value : mixed

the value to be formatted.

Return values
string

the formatted result.

asRelativeTime()

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

public asRelativeTime(int|string|DateTime|DateTimeInterface|DateInterval|null $value[, int|string|DateTime|DateTimeInterface|null $referenceTime = null ]) : string

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.
Parameters
$value : int|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 : int|string|DateTime|DateTimeInterface|null = null

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

Tags
throws
InvalidArgumentException

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

Return values
string

the formatted result.

asScientific()

Formats the value as a scientific number.

public asScientific(mixed $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string
Parameters
$value : mixed

the value to be formatted.

$decimals : int|null = 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<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

Return values
string

the formatted result.

asShortInteger()

Formats the value as short integer number by removing any decimal and thousand digits without rounding.

public asShortInteger(mixed $value[, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string
Parameters
$value : mixed

the value to be formatted.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

Return values
string

the formatted result, e.g. 5K, 123M, 42B, 9T, 1Q

asShortLength()

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

public asShortLength(float|int $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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]].

Parameters
$value : float|int

value to be formatted.

$decimals : int|null = null

the number of digits after the decimal point.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

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

see
asLength
since
2.0.13
author

John Was janek.jan@gmail.com

Return values
string

the formatted result.

asShortSize()

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

public asShortSize(string|int|float|null $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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.

Parameters
$value : string|int|float|null

value in bytes to be formatted.

$decimals : int|null = null

the number of digits after the decimal point.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

see
sizeFormatBase
see
asSize
Return values
string

the formatted result.

asShortWeight()

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

public asShortWeight(float|int $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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]].

Parameters
$value : float|int

value to be formatted.

$decimals : int|null = null

the number of digits after the decimal point.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

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

since
2.0.13
author

John Was janek.jan@gmail.com

Return values
string

the formatted result.

asSize()

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

public asSize(string|int|float|null $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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

Parameters
$value : string|int|float|null

value in bytes to be formatted.

$decimals : int|null = null

the number of digits after the decimal point.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

see
sizeFormatBase
see
asShortSize
Return values
string

the formatted result.

asSpellout()

Formats the value as a number spellout.

public asSpellout(mixed $value) : string

This function requires the PHP intl extension to be installed.

This formatter does not work well with very big numbers.

Parameters
$value : mixed

the value to be formatted

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

when the PHP intl extension is not available.

Return values
string

the formatted result.

asText()

Formats the value as an HTML-encoded plain text.

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

the value to be formatted.

Return values
string

the formatted result.

asTime()

Formats the value as a time.

public asTime(int|string|DateTime|DateTimeInterface|null $value[, string|null $format = null ]) : string
Parameters
$value : int|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 = 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.

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

if the date format is invalid.

see
timeFormat
Return values
string

the formatted result.

asTimestamp()

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

public asTimestamp(int|string|DateTime|DateTimeInterface|null $value) : string
Parameters
$value : int|string|DateTime|DateTimeInterface|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
Return values
string

the formatted result.

asUrl()

Formats the value as a hyperlink.

public asUrl(mixed $value[, array<string|int, mixed> $options = [] ]) : string
Parameters
$value : mixed

the value to be formatted.

$options : array<string|int, mixed> = []

the tag options in terms of name-value pairs. See [[Html::a()]]. Since 2.0.43 there is a special option available scheme - if set it won't be passed to [[Html::a()]] but it will control the URL protocol part of the link by normalizing URL and ensuring that it uses specified scheme. See [[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 values
string

the formatted result.

asWeight()

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

public asWeight(float|int $value[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : string

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]].

Parameters
$value : float|int

value to be formatted.

$decimals : int|null = null

the number of digits after the decimal point.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

throws
InvalidConfigException

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

since
2.0.13
author

John Was janek.jan@gmail.com

Return values
string

the formatted result.

attachBehavior()

Attaches a behavior to this component.

public attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior

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 [[Behavior::attach()]] method.

Parameters
$name : string

the name of the behavior.

$behavior : string|array<string|int, mixed>|Behavior

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

  • a [[Behavior]] object
  • a string specifying the behavior class
  • an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
see
detachBehavior()
Return values
Behavior

the behavior object

attachBehaviors()

Attaches a list of behaviors to the component.

public attachBehaviors(array<string|int, mixed> $behaviors) : mixed

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

Parameters
$behaviors : array<string|int, mixed>

list of behaviors to be attached to the component

Tags
see
attachBehavior()

behaviors()

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

public behaviors() : array<string|int, mixed>

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 [[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).

Return values
array<string|int, mixed>

the behavior configurations.

canGetProperty()

Returns a value indicating whether a property can be read.

public canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canSetProperty()
Return values
bool

whether the property can be read

canSetProperty()

Returns a value indicating whether a property can be set.

public canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
Return values
bool

whether the property can be written

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

detachBehavior()

Detaches a behavior from the component.

public detachBehavior(string $name) : Behavior|null

The behavior's [[Behavior::detach()]] method will be invoked.

Parameters
$name : string

the behavior's name.

Return values
Behavior|null

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

detachBehaviors()

Detaches all behaviors from the component.

public detachBehaviors() : mixed

ensureBehaviors()

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

public ensureBehaviors() : mixed

format()

Formats the value based on the given format type.

public format(mixed $value, string|array<string|int, mixed>|Closure $format) : string

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.

Parameters
$value : mixed

the value to be formatted.

$format : string|array<string|int, mixed>|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.

Tags
throws
InvalidArgumentException

if the format type is not supported by this class.

Return values
string

the formatting result.

getBehavior()

Returns the named behavior object.

public getBehavior(string $name) : Behavior|null
Parameters
$name : string

the behavior name

Return values
Behavior|null

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

getBehaviors()

Returns all behaviors attached to this component.

public getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior>

list of behaviors attached to this component

getDateTimePattern()

Returns the date pattern for the given $locale and $dateType, $timeType.

public getDateTimePattern([int $dateType = IntlDateFormatter::SHORT ][, int $timeType = IntlDateFormatter::SHORT ][, null $locale = null ]) : null|string
Parameters
$dateType : int = IntlDateFormatter::SHORT
$timeType : int = IntlDateFormatter::SHORT
$locale : null = null
Tags
since
1.2.2
Return values
null|string

hasEventHandlers()

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

public hasEventHandlers(string $name) : bool
Parameters
$name : string

the event name

Return values
bool

whether there is any handler attached to the event.

hasMethod()

Returns a value indicating whether a method is defined.

public hasMethod(string $name[, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkBehaviors : bool = true

whether to treat behaviors' methods as methods of this component

Return values
bool

whether the method is defined

hasProperty()

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

public hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

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).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

init()

Initializes the object.

public init() : mixed
Tags
inheritdoc

isShowMeridiem()

Checks if the time pattern of a given $locale contains a meridiem (AM/PM).

public isShowMeridiem([null $locale = null ]) : bool

If no $locale is provided the Formatter locale will be used.

Parameters
$locale : null = null
Tags
since
1.2.2
Return values
bool

if the locale uses a 12 hour (AM/PM) otherwise a 24 hour time format is used.

off()

Detaches an existing event handler from this component.

public off(string $name[, callable|null $handler = null ]) : bool

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.

Parameters
$name : string

event name

$handler : callable|null = null

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

Tags
see
on()
Return values
bool

if a handler is found and detached

on()

Attaches an event handler to an event.

public on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed

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 [[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.');
});
Parameters
$name : string

the event name

$handler : callable

the event handler

$data : mixed = null

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 [[Event::data]].

$append : bool = true

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.

Tags
see
off()

trigger()

Triggers an event.

public trigger(string $name[, Event|null $event = null ]) : mixed

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

Parameters
$name : string

the event name

$event : Event|null = null

the event instance. If not set, a default [[Event]] object will be created.

asCurrencyStringFallback()

Fallback for formatting value as a currency number.

protected asCurrencyStringFallback(string|int|float $value[, string|null $currency = null ]) : string
Parameters
$value : string|int|float

the value to be formatted.

$currency : string|null = null

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

Tags
throws
InvalidConfigException

if no currency is given and [[currencyCode]] is not defined.

since
2.0.16
Return values
string

the formatted result.

asDecimalStringFallback()

Fallback for formatting value as a decimal number.

protected asDecimalStringFallback(string|int|float $value[, int|null $decimals = 2 ]) : string

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

Parameters
$value : string|int|float

the value to be formatted.

$decimals : int|null = 2

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

Tags
see
decimalSeparator
see
thousandSeparator
since
2.0.16
Return values
string

the formatted result.

asIntegerStringFallback()

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

protected asIntegerStringFallback(string|int|float $value) : string
Parameters
$value : string|int|float

the value to be formatted.

Tags
since
2.0.16
Return values
string

the formatted result.

asPercentStringFallback()

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

protected asPercentStringFallback(string|int|float $value[, int|null $decimals = null ]) : string

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

Parameters
$value : string|int|float

the value to be formatted.

$decimals : int|null = null

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

Tags
since
2.0.16
Return values
string

the formatted result.

createNumberFormatter()

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

protected createNumberFormatter(int $style[, int|null $decimals = null ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $textOptions = [] ]) : NumberFormatter

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

Parameters
$style : int

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

$decimals : int|null = null

the number of digits after the decimal point.

$options : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed> = []

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Return values
NumberFormatter

the created formatter instance

formatNumber()

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

protected formatNumber(string|int|float $value, int|null $decimals, int $maxPosition, array<string|int, mixed>|int $formatBase, array<string|int, mixed> $options, array<string|int, mixed> $textOptions) : array<string|int, mixed>
Parameters
$value : string|int|float

value in bytes to be formatted.

$decimals : int|null

the number of digits after the decimal point

$maxPosition : int

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

$formatBase : array<string|int, mixed>|int

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

$options : array<string|int, mixed>

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed>

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidArgumentException

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

since
2.0.32
Return values
array<string|int, mixed>

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

isNormalizedValueMispresented()

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

protected isNormalizedValueMispresented(string|float|int $value, float|int $normalizedValue) : bool
Parameters
$value : string|float|int
$normalizedValue : float|int
Tags
since
2.0.16
Return values
bool

normalizeDatetimeValue()

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

protected normalizeDatetimeValue(int|string|DateTime|DateTimeInterface|null $value[, bool $checkDateTimeInfo = false ]) : DateTime|array<string|int, mixed>
Parameters
$value : int|string|DateTime|DateTimeInterface|null

the datetime value to be normalized. 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
$checkDateTimeInfo : bool = false

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.

Tags
throws
InvalidArgumentException

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

Return values
DateTime|array<string|int, mixed>

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.

normalizeNumericStringValue()

Normalizes a numeric string value.

protected normalizeNumericStringValue(string $value) : string
Parameters
$value : string
Tags
since
2.0.16
Return values
string

the normalized number value as a string

normalizeNumericValue()

Normalizes a numeric input value.

protected normalizeNumericValue(mixed $value) : float|int
  • 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.
Parameters
$value : mixed

the input value

Tags
throws
InvalidArgumentException

if the input value is not numeric.

Return values
float|int

the normalized number value

attachBehaviorInternal()

Attaches a behavior to this component.

private attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
$name : string|int

the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.

$behavior : string|array<string|int, mixed>|Behavior

the behavior to be attached

Return values
Behavior

the attached behavior.

formatDateTimeValue()

private formatDateTimeValue(int|string|DateTime|DateTimeInterface|null $value, string $format, string $type) : string
Parameters
$value : int|string|DateTime|DateTimeInterface|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
$format : string

the format used to convert the value into a date string.

$type : string

'date', 'time', or 'datetime'.

Tags
throws
InvalidConfigException

if the date format is invalid.

Return values
string

the formatted result.

formatUnit()

private formatUnit(string $unitType, string $unitFormat, float|int|null $value, int|null $decimals, array<string|int, mixed> $options, array<string|int, mixed> $textOptions) : string
Parameters
$unitType : string

one of [[UNIT_WEIGHT]], [[UNIT_LENGTH]]

$unitFormat : string

one of [[FORMAT_WIDTH_SHORT]], [[FORMAT_WIDTH_LONG]]

$value : float|int|null

to be formatted

$decimals : int|null

the number of digits after the decimal point.

$options : array<string|int, mixed>

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].

$textOptions : array<string|int, mixed>

optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].

Tags
throws
InvalidConfigException

when INTL is not installed or does not contain required information

Return values
string

getUnitMessage()

private getUnitMessage(string $unitType, string $unitFormat, string|null $system, int $position) : string
Parameters
$unitType : string

one of [[UNIT_WEIGHT]], [[UNIT_LENGTH]]

$unitFormat : string

one of [[FORMAT_WIDTH_SHORT]], [[FORMAT_WIDTH_LONG]]

$system : string|null

either [[UNIT_SYSTEM_METRIC]] or [[UNIT_SYSTEM_IMPERIAL]]. When null, property [[systemOfUnits]] will be used.

$position : int

internal position of size unit

Tags
throws
InvalidConfigException

when INTL is not installed or does not contain required information

Return values
string

setFormatterIntAttribute()

private setFormatterIntAttribute(NumberFormatter $formatter, mixed $attribute, mixed $value, string $source, string $alternative) : mixed
Parameters
$formatter : NumberFormatter
$attribute : mixed
$value : mixed
$source : string
$alternative : string

setFormatterSymbol()

private setFormatterSymbol(NumberFormatter $formatter, mixed $symbol, mixed $value, string $source) : mixed
Parameters
$formatter : NumberFormatter
$symbol : mixed
$value : mixed
$source : string

setFormatterTextAttribute()

private setFormatterTextAttribute(NumberFormatter $formatter, mixed $attribute, mixed $value, string $source, string $alternative) : mixed
Parameters
$formatter : NumberFormatter
$attribute : mixed
$value : mixed
$source : string
$alternative : string

        
On this page

Search results