yii\i18n\Formatter::format PHP Method

format() public method

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 Formatter::asHtml will be used. Format names are case insensitive.
public format ( mixed $value, string | array $format ) : string
$value mixed the value to be formatted.
$format string | array the format of the value, e.g., "html", "text". 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')`.
return string the formatting result.
    public function format($value, $format)
    {
        if (is_array($format)) {
            if (!isset($format[0])) {
                throw new InvalidParamException('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);
        } else {
            throw new InvalidParamException("Unknown format type: {$format}");
        }
    }

Usage Example

Beispiel #1
0
 public function testFormat()
 {
     $value = time();
     $this->assertSame(date('M j, Y', $value), $this->formatter->format($value, 'date'));
     $this->assertSame(date('M j, Y', $value), $this->formatter->format($value, 'DATE'));
     $this->assertSame(date('Y/m/d', $value), $this->formatter->format($value, ['date', 'php:Y/m/d']));
     $this->setExpectedException('\\yii\\base\\InvalidParamException');
     $this->assertSame(date('Y-m-d', $value), $this->formatter->format($value, 'data'));
 }
All Usage Examples Of yii\i18n\Formatter::format