Exemplo n.º 1
0
 protected function log($writeToLogFunction, $level, $levelName, $message, $params)
 {
     $minimalLevel = $this->_minimalLevels ? Arrays::getValue($this->_minimalLevels, $this->_name, LOG_DEBUG) : LOG_DEBUG;
     if ($level <= $minimalLevel) {
         $message = $this->_messageFormatter->format($this->_name, $levelName, $message);
         if (!empty($params)) {
             $message = call_user_func_array('sprintf', array_merge(array($message), $params));
         }
         $writeToLogFunction($message);
     }
 }
Exemplo n.º 2
0
 /**
  * {@inheritdoc}
  *
  * @param string     $index
  * @param null|array $placeholders
  */
 public function query($index, $placeholders = null)
 {
     if (!$this->exists($index)) {
         return $index;
     }
     $formatter = new \MessageFormatter($this->options['locale'], $this->get($index, $this->bundle));
     if (null !== $formatter) {
         return $formatter->format((array) $placeholders);
     } else {
         return $index;
     }
 }
 /**
  * Formats the message with the help of php intl extension.
  * 
  * @param string $locale
  * @param string $message
  * @param array(string=>mixed) $parameters
  * @return string
  * @throws CannotInstantiateFormatterException If the message pattern cannot be used.
  * @throws CannotFormatException If an error occurs during formatting.
  */
 public function format($locale, $message, array $parameters)
 {
     if (empty($message)) {
         // Empty strings are not accepted as message pattern by the \MessageFormatter.
         return $message;
     }
     try {
         $formatter = new \MessageFormatter($locale, $message);
     } catch (\Exception $e) {
         throw new CannotInstantiateFormatterException($e->getMessage(), $e->getCode(), $e);
     }
     if (!$formatter) {
         throw new CannotInstantiateFormatterException(intl_get_error_message(), intl_get_error_code());
     }
     $result = $formatter->format($parameters);
     if ($result === false) {
         throw new CannotFormatException($formatter->getErrorMessage(), $formatter->getErrorCode());
     }
     return $result;
 }
Exemplo n.º 4
0
<?php

// Prints € 4 560
$formatter = new MessageFormatter("fr_FR", "€ {0, number, integer}");
echo $formatter->format(array(4560));
// Prints USD$ 4,560.5
$formatter = new MessageFormatter("en_US", "USD\$ {0, number}");
echo $formatter->format(array(4560.5));
// Prints ARS$ 1.250,25
$formatter = new MessageFormatter("es_AR", "ARS\$ {0, number}");
echo $formatter->format(array(1250.25));
Exemplo n.º 5
0
 /**
  * Provided that the HTML tag contains ICU-compatible message format
  * string, it will be localized then integrated with passed arguments
  */
 function setMessage($tag, $args = array())
 {
     if (!is_array($args)) {
         $args = array($args);
     }
     $fmt = $this->app->_($this->get($tag));
     // Try to analyze format and see which formatter to use
     if (class_exists('MessageFormatter', false) && strpos($fmt, '{') !== null) {
         $fmt = new MessageFormatter($this->app->locale, $fmt);
         $str = $fmt->format($args);
     } elseif (strpos($fmt, '%') !== null) {
         array_unshift($args, $fmt);
         $str = call_user_func_array('sprintf', $args);
     } else {
         throw $this->exception('Unclear how to format this')->addMoreInfo('fmt', $fmt);
     }
     return $this->set($tag, $str);
 }
Exemplo n.º 6
0
<?php

$message = '{0, select, f {She} m {He} other {It}} went to the store.';
$fmt = new MessageFormatter('en_US', $message);
print $fmt->format(array('f')) . "\n";
print $fmt->format(array('m')) . "\n";
print $fmt->format(array('Unknown')) . "\n";
Exemplo n.º 7
0
 /**
  * This is the main parsing method.
  *
  * \param DOMNode $node
  *      The node being parsed.
  *
  * \param array $attributes
  *      Array of styling attributes.
  *
  * \param array $vars
  *      Template variables that can be injected in the return.
  *
  * \retval string
  *      Parsing result, with styles applied as appropriate.
  */
 protected function parseNode($node, &$attributes, $vars)
 {
     $result = '';
     $saved = $attributes;
     if ($node->nodeType == XML_TEXT_NODE) {
         return $node->nodeValue;
     }
     if ($node->nodeType != XML_ELEMENT_NODE) {
         return '';
     }
     // Pre-handling.
     switch ($node->tagName) {
         case 'var':
             $lexer = new \Erebot\Styling\Lexer($node->getAttribute('name'), $vars);
             $var = $lexer->getResult();
             if (!$var instanceof \Erebot\Styling\VariableInterface) {
                 return (string) $var;
             }
             return $var->render($this->translator);
         case 'u':
             if (!$attributes['underline']) {
                 $result .= self::CODE_UNDERLINE;
             }
             $attributes['underline'] = 1;
             break;
         case 'b':
             if (!$attributes['bold']) {
                 $result .= self::CODE_BOLD;
             }
             $attributes['bold'] = 1;
             break;
         case 'color':
             $colors = array('', '');
             $mapping = array('fg', 'bg');
             foreach ($mapping as $pos => $color) {
                 $value = $node->getAttribute($color);
                 if ($value != '') {
                     $value = str_replace(array(' ', '-'), '_', $value);
                     if (strspn($value, '1234567890') !== strlen($value)) {
                         $reflector = new \ReflectionClass('\\Erebot\\StylingInterface');
                         if (!$reflector->hasConstant('COLOR_' . strtoupper($value))) {
                             throw new \InvalidArgumentException('Invalid color "' . $value . '"');
                         }
                         $value = $reflector->getConstant('COLOR_' . strtoupper($value));
                     }
                     $attributes[$color] = sprintf('%02d', $value);
                     if ($attributes[$color] != $saved[$color]) {
                         $colors[$pos] = $attributes[$color];
                     }
                 }
             }
             $code = implode(',', $colors);
             if ($colors[0] != '' && $colors[1] != '') {
                 $result .= self::CODE_COLOR . $code;
             } elseif ($code != ',') {
                 $result .= self::CODE_COLOR . rtrim($code, ',') . self::CODE_BOLD . self::CODE_BOLD;
             }
             break;
     }
     if ($node->tagName == 'for') {
         // Handle loops.
         $savedVariables = $vars;
         $separator = array(', ', ' & ');
         foreach (array('separator', 'sep') as $attr) {
             $attrNode = $node->getAttributeNode($attr);
             if ($attrNode !== false) {
                 $separator[0] = $separator[1] = $attrNode->nodeValue;
                 break;
             }
         }
         foreach (array('last_separator', 'last') as $attr) {
             $attrNode = $node->getAttributeNode($attr);
             if ($attrNode !== false) {
                 $separator[1] = $attrNode->nodeValue;
                 break;
             }
         }
         $loopKey = $node->getAttribute('key');
         $loopItem = $node->getAttribute('item');
         $loopFrom = $node->getAttribute('from');
         $count = count($vars[$loopFrom]);
         reset($vars[$loopFrom]);
         for ($i = 1; $i < $count; $i++) {
             if ($i > 1) {
                 $result .= $separator[0];
             }
             $item = each($vars[$loopFrom]);
             if ($loopKey !== null) {
                 $cls = $this->cls['string'];
                 $vars[$loopKey] = new $cls($item['key']);
             }
             $vars[$loopItem] = $this->wrapScalar($item['value'], $loopItem);
             $result .= $this->parseChildren($node, $attributes, $vars);
         }
         $item = each($vars[$loopFrom]);
         if ($item === false) {
             $item = array('key' => '', 'value' => '');
         }
         if ($loopKey !== null) {
             $cls = $this->cls['string'];
             $vars[$loopKey] = new $cls($item['key']);
         }
         $vars[$loopItem] = $this->wrapScalar($item['value'], $loopItem);
         if ($count > 1) {
             $result .= $separator[1];
         }
         $result .= $this->parseChildren($node, $attributes, $vars);
         $vars = $savedVariables;
     } elseif ($node->tagName == 'plural') {
         // Handle plurals.
         /* We don't need the full set of features/complexity/bugs
          * ICU contains. Here, we use a simple "plural" formatter
          * to detect the right plural form to use. The formatting
          * steps are done without relying on ICU. */
         $attrNode = $node->getAttributeNode('var');
         if ($attrNode === false) {
             throw new \InvalidArgumentException('No variable name given');
         }
         $lexer = new \Erebot\Styling\Lexer($attrNode->nodeValue, $vars);
         $value = $lexer->getResult();
         if ($value instanceof \Erebot\Styling\VariableInterface) {
             $value = $value->getValue();
         }
         $value = (int) $value;
         $subcontents = array();
         $pattern = '{0,plural,';
         for ($child = $node->firstChild; $child != null; $child = $child->nextSibling) {
             if ($child->nodeType != XML_ELEMENT_NODE || $child->tagName != 'case') {
                 continue;
             }
             // See this class documentation for a link
             // which lists available forms for each language.
             $form = $child->getAttribute('form');
             $subcontents[$form] = $this->parseNode($child, $attributes, $vars);
             $pattern .= $form . '{' . $form . '} ';
         }
         $pattern .= '}';
         $locale = $this->translator->getLocale(\Erebot\IntlInterface::LC_MESSAGES);
         $formatter = new \MessageFormatter($locale, $pattern);
         // HACK: PHP <= 5.3.3 returns null when the pattern in invalid
         // instead of throwing an exception.
         // See http://bugs.php.net/bug.php?id=52776
         if ($formatter === null) {
             throw new \InvalidArgumentException('Invalid plural forms');
         }
         $correctForm = $formatter->format(array($value));
         $result .= $subcontents[$correctForm];
     } else {
         // Handle children.
         $result .= $this->parseChildren($node, $attributes, $vars);
     }
     // Post-handling : restore old state.
     switch ($node->tagName) {
         case 'u':
             if (!$saved['underline']) {
                 $result .= self::CODE_UNDERLINE;
             }
             $attributes['underline'] = 0;
             break;
         case 'b':
             if (!$saved['bold']) {
                 $result .= self::CODE_BOLD;
             }
             $attributes['bold'] = 0;
             break;
         case 'color':
             $colors = array('', '');
             $mapping = array('fg', 'bg');
             foreach ($mapping as $pos => $color) {
                 if ($attributes[$color] != $saved[$color]) {
                     $colors[$pos] = $saved[$color];
                 }
                 $attributes[$color] = $saved[$color];
             }
             $code = implode(',', $colors);
             if ($colors[0] != '' && $colors[1] != '') {
                 $result .= self::CODE_COLOR . $code;
             } elseif ($code != ',') {
                 $result .= self::CODE_COLOR . rtrim($code, ',') . self::CODE_BOLD . self::CODE_BOLD;
             }
             break;
     }
     return $result;
 }
<?php

/* This might come from user input or the browser */
define('LOCALE', 'en_US');
/* If you can't trust the locale, add some error checking
 * in case the file doesn't exist or can't be
 * unserialized. */
$messages = unserialize(file_get_contents(__DIR__ . '/' . LOCALE . '.ser'));
$candy = new MessageFormatter(LOCALE, $messages['CANDY']);
$favs = new MessageFormatter(LOCALE, $messages['FAVORITE_FOODS']);
print $favs->format(array($candy->format(array()))) . "\n";
Exemplo n.º 9
0
 /**
  * Middleware that logs requests, responses, and errors using a message
  * formatter.
  *
  * @param LoggerInterface  $logger Logs messages.
  * @param MessageFormatter $formatter Formatter used to create message strings.
  * @param string           $logLevel Level at which to log requests.
  *
  * @return callable Returns a function that accepts the next handler.
  */
 public static function log(LoggerInterface $logger, MessageFormatter $formatter, $logLevel = LogLevel::INFO)
 {
     return function (callable $handler) use($logger, $formatter, $logLevel) {
         return function ($request, array $options) use($handler, $logger, $formatter, $logLevel) {
             return $handler($request, $options)->then(function ($response) use($logger, $request, $formatter, $logLevel) {
                 $message = $formatter->format($request, $response);
                 $logger->log($logLevel, $message);
                 return $response;
             }, function ($reason) use($logger, $request, $formatter) {
                 $response = $reason instanceof RequestException ? $reason->getResponse() : null;
                 $message = $formatter->format($request, $response, $reason);
                 $logger->notice($message);
                 return \GuzzleHttp\Promise\rejection_for($reason);
             });
         };
     };
 }
Exemplo n.º 10
0
<?php

$args = array(7, 159, -0.3782, 6.815574);
$messages = array("0", "00", "1", "11", "222", "#", "##", "@", "@@@", "##%", "¤#", "¤1.11", "¤¤#", "#.##;(#.## !!!)");
foreach ($messages as $message) {
    $fmt = new MessageFormatter('en_US', "{0,number,{$message}}\t{1,number,{$message}}\t" . "{2,number,{$message}}\t{3,number,{$message}}");
    print "{$message}:\t" . $fmt->format($args) . "\n";
}
Exemplo n.º 11
0
<?php

ini_set("intl.error_level", E_WARNING);
$fmt = <<<EOD
{foo}
EOD;
$mf = new MessageFormatter('en_US', $fmt);
var_dump($mf->format(array("foo" => 'bar', 7 => fopen('php://memory', 'r+'))));
Exemplo n.º 12
0
<?php

ini_set("intl.error_level", E_WARNING);
//ini_set("intl.default_locale", "nl");
$fmt = <<<EOD
{0,date} {0,time}
EOD;
$dt = new DateTime("2012-05-06 18:00:42", new DateTimeZone("Europe/Lisbon"));
$mf = new MessageFormatter('en_US', $fmt);
var_dump($mf->format(array($dt)));
?>
==DONE==
Exemplo n.º 13
0
/**
 * Format date
 *
 * @param string $date
 * @param string $lang
 * @return string
 */
function date_time_format($date, $lang = 'en_US')
{
    $formatter = new MessageFormatter($lang, "{0, date}");
    return $formatter->format([strtotime($date)]);
}
Exemplo n.º 14
0
<?php

ini_set("intl.error_level", E_WARNING);
//ini_set("intl.default_locale", "nl");
ini_set('date.timezone', 'Europe/Lisbon');
$cal = new IntlGregorianCalendar(2012, 04, 17, 17, 35, 36);
$msgf = new MessageFormatter('pt_PT', '{0,date,full} {0,time,h:m:s a V}');
echo $msgf->format(array($cal)), "\n";
//NOT FIXED:
/*$msgf = new MessageFormatter('en_US',
'{1, select, date {{0,date,full}} other {{0,time,h:m:s a V}}}');

echo "msgf2: ", $msgf->format(array($time, 'date')), " ",
		$msgf->format(array($time, 'time')), "\n";
*/
?>
==DONE==
<?php

$when = 1376943432;
// Seconds since epoch
$message = "Maintenant: {0,date,eeee dd MMMM y}";
$fmt = new MessageFormatter('fr_FR', $message);
print $fmt->format(array($when));
Exemplo n.º 16
0
<?php

ini_set("intl.error_level", E_WARNING);
date_default_timezone_set('Europe/Lisbon');
//ignored for now, see bug #58756
$d = 1336308097.123;
$mf = new MessageFormatter('en_US', "On {0,time,yyyy-MM-dd G 'at' HH:mm:ss.SSS zzz} something odd happened");
var_dump($mf->format(array(1336310569.123)));
$p = 'On 2012-05-06 AD at 15:22:49.123 GMT+02:00 something odd happened';
var_dump($mf->parse($p));
?>
==DONE==
Exemplo n.º 17
0
 /**
  * Translate the $resource
  *
  * @param string               $locale
  * @param TranslatableResource $resource
  *
  * @throws \IntlException
  * @return string
  */
 public function translate($locale, TranslatableResource $resource)
 {
     $canonicalLocale = \Locale::canonicalize($locale);
     $messageFormatter = new \MessageFormatter($canonicalLocale, $this->retrievePattern($canonicalLocale, $resource->getKey()));
     return $messageFormatter->format($resource->getParameters());
 }
Exemplo n.º 18
0
<?php

ini_set("intl.error_level", E_WARNING);
$fmt = <<<EOD
{foo,date}
EOD;
$mf = new MessageFormatter('en_US', $fmt);
var_dump($mf->format(array("foo" => new stdclass())));
Exemplo n.º 19
0
<?php

$message = 'I like to eat {food} and {drink}.';
$fmt = new MessageFormatter('en_US', $message);
print $fmt->format(array('food' => 'eggs', 'drink' => 'water'));
    /**
     * @covers Intacct\Logging\MessageFormatter::format
     */
    public function testRequestAndResponseRemoval()
    {
        $config = ['control_id' => 'unittest', 'sender_id' => 'testsenderid', 'sender_password' => 'pass123!', 'company_id' => 'testcompany', 'user_id' => 'testuser', 'user_password' => 'P@ssW0rd!123'];
        $contentBlock = new Content([new ApiSessionCreate('unittest')]);
        $xmlRequest = new RequestBlock($config, $contentBlock);
        $xmlResponse = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<response>
    <control>
        <status>success</status>
        <senderid>testsenderid</senderid>
        <controlid>testControl</controlid>
        <uniqueid>false</uniqueid>
        <dtdversion>3.0</dtdversion>
    </control>
    <operation>
        <authentication>
            <status>success</status>
            <userid>testuser</userid>
            <companyid>testcompany</companyid>
            <sessiontimestamp>2016-08-22T10:58:43-07:00</sessiontimestamp>
        </authentication>
        <result>
            <status>success</status>
            <function>get_list</function>
            <controlid>test1</controlid>
            <listtype start="0" end="0" total="1">vendor</listtype>
            <data>
                <vendor>
                    <recordno>4</recordno>
                    <vendorid>V0004</vendorid>
                    <name>Vendor 4</name>
                    <taxid>99-9999999</taxid>
                    <achenabled>true</achenabled>
                    <achaccountnumber>1111222233334444</achaccountnumber>
                    <achaccounttype>Checking Account</achaccounttype>
                </vendor>
            </data>
        </result>
        <result>
            <status>success</status>
            <function>readByQuery</function>
            <controlid>test2</controlid>
            <data listtype="vendor" count="1" totalcount="1" numremaining="0" resultId="">
                <vendor>
                    <RECORDNO>4</RECORDNO>
                    <VENDORID>V0004</VENDORID>
                    <NAME>Vendor 4</NAME>
                    <TAXID>99-9999999</TAXID>
                    <ACHENABLED>true</ACHENABLED>
                    <ACHACCOUNTNUMBER>1111222233334444</ACHACCOUNTNUMBER>
                    <ACHACCOUNTTYPE>Checking Account</ACHACCOUNTTYPE>
                </vendor>
            </data>
        </result>
    </operation>
</response>
EOF;
        $mockRequest = new Request('POST', 'https://unittest.intacct.com', [], $xmlRequest->writeXml()->flush());
        $mockResponse = new Response(200, [], $xmlResponse);
        $formatter = new MessageFormatter("{req_body}/n/r{res_body}");
        $message = $formatter->format($mockRequest, $mockResponse);
        $this->assertNotContains('<password>pass123!</password>', $message);
        $this->assertNotContains('<password>P@ssW0rd!123</password>', $message);
        $this->assertContains('<password>REDACTED</password>', $message);
        $this->assertNotContains('<taxid>99-9999999</taxid>', $message);
        $this->assertNotContains('<TAXID>99-9999999</TAXID>', $message);
        $this->assertContains('<taxid>REDACTED</taxid>', $message);
        $this->assertContains('<TAXID>REDACTED</TAXID>', $message);
        $this->assertNotContains('<achaccountnumber>1111222233334444</achaccountnumber>', $message);
        $this->assertNotContains('<ACHACCOUNTNUMBER>1111222233334444</ACHACCOUNTNUMBER>', $message);
        $this->assertContains('<achaccountnumber>REDACTED</achaccountnumber>', $message);
        $this->assertContains('<ACHACCOUNTNUMBER>REDACTED</ACHACCOUNTNUMBER>', $message);
    }
Exemplo n.º 21
0
 /**
  * Formats a message via [ICU message format](http://userguide.icu-project.org/formatparse/messages)
  *
  * It uses the PHP intl extension's [MessageFormatter](http://www.php.net/manual/en/class.messageformatter.php)
  * and works around some issues.
  * If PHP intl is not installed a fallback will be used that supports a subset of the ICU message format.
  *
  * @param string $pattern The pattern string to insert parameters into.
  * @param array $params The array of name value pairs to insert into the format string.
  * @param string $language The locale to use for formatting locale-dependent parts
  * @return string|bool The formatted pattern string or `FALSE` if an error occurred
  */
 public function format($pattern, $params, $language)
 {
     $this->_errorCode = 0;
     $this->_errorMessage = '';
     if ($params === []) {
         return $pattern;
     }
     if (!class_exists('MessageFormatter', false)) {
         return $this->fallbackFormat($pattern, $params, $language);
     }
     // replace named arguments (https://github.com/yiisoft/yii2/issues/9678)
     $newParams = [];
     $pattern = $this->replaceNamedArguments($pattern, $params, $newParams);
     $params = $newParams;
     try {
         $formatter = new \MessageFormatter($language, $pattern);
         if ($formatter === null) {
             // formatter may be null in PHP 5.x
             $this->_errorCode = intl_get_error_code();
             $this->_errorMessage = 'Message pattern is invalid: ' . intl_get_error_message();
             return false;
         }
     } catch (\IntlException $e) {
         // IntlException is thrown since PHP 7
         $this->_errorCode = $e->getCode();
         $this->_errorMessage = 'Message pattern is invalid: ' . $e->getMessage();
         return false;
     } catch (\Exception $e) {
         // Exception is thrown by HHVM
         $this->_errorCode = $e->getCode();
         $this->_errorMessage = 'Message pattern is invalid: ' . $e->getMessage();
         return false;
     }
     $result = $formatter->format($params);
     if ($result === false) {
         $this->_errorCode = $formatter->getErrorCode();
         $this->_errorMessage = $formatter->getErrorMessage();
         return false;
     } else {
         return $result;
     }
 }
Exemplo n.º 22
0
<?php

ini_set("intl.error_level", E_WARNING);
//ini_set("intl.default_locale", "nl");
$mf = new MessageFormatter('en_US', "{0,number} -- {1,ordinal}");
var_dump($mf->format(array(1.3, 1.3)));
var_dump($mf->format(array(1.3, 1.3)));
$mf->setPattern("{0,ordinal} -- {1,number}");
var_dump($mf->format(array(1.3, 1.3)));
?>
==DONE==
 /**
  * Formats a message via [ICU message format](http://userguide.icu-project.org/formatparse/messages)
  *
  * It uses the PHP intl extension's [MessageFormatter](http://www.php.net/manual/en/class.messageformatter.php)
  * and works around some issues.
  * If PHP intl is not installed a fallback will be used that supports a subset of the ICU message format.
  *
  * @param string $pattern The pattern string to insert parameters into.
  * @param array $params The array of name value pairs to insert into the format string.
  * @param string $language The locale to use for formatting locale-dependent parts
  * @return string|boolean The formatted pattern string or `FALSE` if an error occurred
  */
 public function format($pattern, $params, $language)
 {
     $this->_errorCode = 0;
     $this->_errorMessage = '';
     if ($params === []) {
         return $pattern;
     }
     if (!class_exists('MessageFormatter', false)) {
         return $this->fallbackFormat($pattern, $params, $language);
     }
     if (version_compare(PHP_VERSION, '5.5.0', '<') || version_compare(INTL_ICU_VERSION, '4.8', '<')) {
         // replace named arguments
         $pattern = $this->replaceNamedArguments($pattern, $params, $newParams);
         $params = $newParams;
     }
     $formatter = new \MessageFormatter($language, $pattern);
     if ($formatter === null) {
         $this->_errorCode = intl_get_error_code();
         $this->_errorMessage = "Message pattern is invalid: " . intl_get_error_message();
         return false;
     }
     $result = $formatter->format($params);
     if ($result === false) {
         $this->_errorCode = $formatter->getErrorCode();
         $this->_errorMessage = $formatter->getErrorMessage();
         return false;
     } else {
         return $result;
     }
 }
Exemplo n.º 24
0
<?php

ini_set("intl.error_level", E_WARNING);
//ini_set("intl.default_locale", "nl");
$mf = new MessageFormatter('en_US', "{0,number} -- {foo,ordinal}");
var_dump($mf->format(array(2.3, "foo" => 1.3)));
var_dump($mf->format(array("foo" => 1.3, 0 => 2.3)));
?>
==DONE==
<?php

ini_set("intl.error_level", E_WARNING);
//ini_set("intl.default_locale", "nl");
$mf = new MessageFormatter('en_US', "\n\tnone\t\t\t{a}\n\tnumber\t\t\t{b,number}\n\tnumber integer\t{c,number,integer}\n\tnumber currency\t{d,number,currency}\n\tnumber percent\t{e,number,percent}\n\tdate\t\t\t{f,date}\n\ttime\t\t\t{g,time}\n\tspellout\t\t{h,spellout}\n\tordinal\t\t\t{i,ordinal}\n\tduration\t\t{j,duration}\n\t");
$ex = "1336317965.5 str";
var_dump($mf->format(array('a' => $ex, 'b' => $ex, 'c' => $ex, 'd' => $ex, 'e' => $ex, 'f' => "  1336317965.5", 'g' => "  1336317965.5", 'h' => $ex, 'i' => $ex, 'j' => $ex)));
?>
==DONE==
Exemplo n.º 26
0
<?php

ini_set("intl.error_level", E_WARNING);
$fmt = <<<EOD
{foo,number} {foo}
EOD;
$mf = new MessageFormatter('en_US', $fmt);
var_dump($mf->format(array(7)));
Exemplo n.º 27
0
 /**
  * Formats a message via [ICU message format](http://userguide.icu-project.org/formatparse/messages)
  *
  * It uses the PHP intl extension's [MessageFormatter](http://www.php.net/manual/en/class.messageformatter.php)
  * and works around some issues.
  * If PHP intl is not installed a fallback will be used that supports a subset of the ICU message format.
  *
  * @param string $pattern The pattern string to insert parameters into.
  * @param array $params The array of name value pairs to insert into the format string.
  * @param string $language The locale to use for formatting locale-dependent parts
  * @return string|boolean The formatted pattern string or `FALSE` if an error occurred
  */
 public function format($pattern, $params, $language)
 {
     $this->_errorCode = 0;
     $this->_errorMessage = '';
     if ($params === []) {
         return $pattern;
     }
     if (!class_exists('MessageFormatter', false)) {
         return $this->fallbackFormat($pattern, $params, $language);
     }
     // replace named arguments (https://github.com/yiisoft/yii2/issues/9678)
     $pattern = $this->replaceNamedArguments($pattern, $params, $newParams);
     $params = $newParams;
     $formatter = new \MessageFormatter($language, $pattern);
     if ($formatter === null) {
         $this->_errorCode = intl_get_error_code();
         $this->_errorMessage = "Message pattern is invalid: " . intl_get_error_message();
         return false;
     }
     $result = $formatter->format($params);
     if ($result === false) {
         $this->_errorCode = $formatter->getErrorCode();
         $this->_errorMessage = $formatter->getErrorMessage();
         return false;
     } else {
         return $result;
     }
 }
<?php

ini_set("intl.error_level", E_WARNING);
//ini_set("intl.default_locale", "nl");
$time = 1247013673;
ini_set('date.timezone', 'America/New_York');
$msgf = new MessageFormatter('en_US', '{0,date,full} {0,time,h:m:s a V}');
echo "date:  " . date('l, F j, Y g:i:s A T', $time) . "\n";
echo "msgf:  " . $msgf->format(array($time)) . "\n";
//NOT FIXED:
/*$msgf = new MessageFormatter('en_US',
'{1, select, date {{0,date,full}} other {{0,time,h:m:s a V}}}');

echo "msgf2: ", $msgf->format(array($time, 'date')), " ",
		$msgf->format(array($time, 'time')), "\n";
*/
?>
==DONE==
Exemplo n.º 29
0
<?php

ini_set("intl.error_level", E_WARNING);
$fmt = <<<EOD
{foo,number,percent}
EOD;
$mf = new MessageFormatter('en_US', $fmt);
var_dump($mf->format(array("foo" => 7, -1 => "bar")));
Exemplo n.º 30
0
<?php

$message = '{0,number} / {1,number} = {2,number}';
$args = array(5327, 98, 5327 / 98);
$us = new MessageFormatter('en_US', $message);
$fr = new MessageFormatter('fr_FR', $message);
print $us->format($args) . "\n";
print $fr->format($args) . "\n";