Example #1
0
function ut_main()
{
    $ret = var_export(ut_loc_get_display_name(str_repeat('*', 256), 'en_us'), true);
    $ret .= "\n";
    $ret .= var_export(intl_get_error_message(), true);
    return $ret;
}
function ut_main()
{
    $locale_arr = array('en_US_CA');
    $datetype_arr = array(IntlDateFormatter::FULL, IntlDateFormatter::LONG, IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
    $res_str = '';
    $text_arr = array("Sunday, September 18, 3039 4:06:40 PM PT", "Thursday, December 18, 1969 8:49:59 AM PST", "12/18/69 8:49 AM", "20111218 08:49 AM", "19691218 08:49 AM");
    foreach ($text_arr as $text_entry) {
        $res_str .= "\n------------\n";
        $res_str .= "\nInput text is : {$text_entry}";
        $res_str .= "\n------------";
        foreach ($locale_arr as $locale_entry) {
            $res_str .= "\nLocale is : {$locale_entry}";
            $res_str .= "\n------------";
            foreach ($datetype_arr as $datetype_entry) {
                $res_str .= "\ndatetype = {$datetype_entry} ,timetype ={$datetype_entry}";
                $fmt = ut_datefmt_create($locale_entry, $datetype_entry, $datetype_entry);
                $pos = 0;
                $parsed = ut_datefmt_parse($fmt, $text_entry, $pos);
                if (intl_get_error_code() == U_ZERO_ERROR) {
                    $res_str .= "\nParsed text is : {$parsed}; Position = {$pos}";
                } else {
                    $res_str .= "\nError while parsing as: '" . intl_get_error_message() . "'; Position = {$pos}";
                }
            }
        }
    }
    $res_str .= "\n";
    return $res_str;
}
function ut_main()
{
    $pattern = <<<_MSG_
{0, select,
  female {{1, plural, offset:1
      =0 {{2} does not give a party.}
      =1 {{2} invites {3} to her party.}
      =2 {{2} invites {3} and one other person to her party.}
     other {{2} invites {3} as one of the # people invited to her party.}}}
  male   {{1, plural, offset:1
      =0 {{2} does not give a party.}
      =1 {{2} invites {3} to his party.}
      =2 {{2} invites {3} and one other person to his party.}
     other {{2} invites {3} as one of the # other people invited to his party.}}}
  other {{1, plural, offset:1
      =0 {{2} does not give a party.}
      =1 {{2} invites {3} to their party.}
      =2 {{2} invites {3} and one other person to their party.}
      other {{2} invites {3} as one of the # other people invited to their party.}}}}
_MSG_;
    $args = array(array('female', 0, 'Alice', 'Bob'), array('male', 1, 'Alice', 'Bob'), array('none', 2, 'Alice', 'Bob'), array('female', 27, 'Alice', 'Bob'));
    $str_res = '';
    $fmt = ut_msgfmt_create('en_US', $pattern);
    if (!$fmt) {
        $str_res .= dump(intl_get_error_message()) . "\n";
        return $str_res;
    }
    foreach ($args as $arg) {
        $str_res .= dump(ut_msgfmt_format($fmt, $arg)) . "\n";
        $str_res .= dump(ut_msgfmt_format_message('en_US', $pattern, $arg)) . "\n";
    }
    return $str_res;
}
function ut_main()
{
    $pattern = <<<_MSG_
{gender_of_host, select,
  female {{num_guests, plural, offset:1
      =0 {{host} does not give a party.}
      =1 {{host} invites {guest} to her party.}
      =2 {{host} invites {guest} and one other person to her party.}
     other {{host} invites {guest} as one of the # people invited to her party.}}}
  male   {{num_guests, plural, offset:1
      =0 {{host} does not give a party.}
      =1 {{host} invites {guest} to his party.}
      =2 {{host} invites {guest} and one other person to his party.}
     other {{host} invites {guest} as one of the # people invited to his party.}}}
  other {{num_guests, plural, offset:1
      =0 {{host} does not give a party.}
      =1 {{host} invites {guest} to their party.}
      =2 {{host} invites {guest} and one other person to their party.}
     other {{host} invites {guest} as one of the # people invited to their party.}}}}
_MSG_;
    $args = array(array('gender_of_host' => 'female', 'num_guests' => 0, 'host' => 'Alice', 'guest' => 'Bob'), array('gender_of_host' => 'male', 'num_guests' => 1, 'host' => 'Alice', 'guest' => 'Bob'), array('gender_of_host' => 'none', 'num_guests' => 2, 'host' => 'Alice', 'guest' => 'Bob'), array('gender_of_host' => 'female', 'num_guests' => 27, 'host' => 'Alice', 'guest' => 'Bob'));
    $str_res = '';
    $fmt = ut_msgfmt_create('en_US', $pattern);
    if (!$fmt) {
        $str_res .= dump(intl_get_error_message()) . "\n";
        return $str_res;
    }
    foreach ($args as $arg) {
        $str_res .= dump(ut_msgfmt_format($fmt, $arg)) . "\n";
        $str_res .= dump(ut_msgfmt_format_message('en_US', $pattern, $arg)) . "\n";
    }
    return $str_res;
}
function ut_main()
{
    $locale_arr = array('en_US_CA');
    $datetype_arr = array(IntlDateFormatter::FULL, IntlDateFormatter::LONG, IntlDateFormatter::MEDIUM);
    $res_str = '';
    $text_arr = array("Thursday, December 18, 1969 8:49:59 AM PST", "June 18, 1969 8:49:59 AM ", "12/18/69 8:49 AM", "19691218 08:49 AM");
    $fmt1 = ut_datefmt_create('en_US_CA', IntlDateFormatter::LONG, IntlDateFormatter::LONG);
    $fmt2 = ut_datefmt_create('en_US_CA', IntlDateFormatter::MEDIUM, IntlDateFormatter::MEDIUM);
    $fmt3 = ut_datefmt_create('en_US_CA', IntlDateFormatter::FULL, IntlDateFormatter::FULL);
    $fmt_array = array($fmt1, $fmt2, $fmt3);
    $fmt_desc_array = array("DateType::LONG, TimeType::LONG", "DateType::MEDIUM, TimeType::MEDIUM", "DateType::FULL, TimeType::FULL");
    foreach ($text_arr as $text_entry) {
        $res_str .= "\n-------------------------------\n";
        $res_str .= "\nInput text is : {$text_entry}";
        $cnt = 0;
        foreach ($fmt_array as $fmt_entry) {
            $res_str .= "\n------------";
            $res_str .= "\nIntlDateFormatter : " . $fmt_desc_array[$cnt];
            $cnt++;
            $parsed_arr = ut_datefmt_localtime($fmt_entry, $text_entry);
            if ($parsed_arr) {
                $res_str .= "\n";
                foreach ($parsed_arr as $key => $value) {
                    $res_str .= "{$key} : '{$value}' , ";
                }
            } else {
                //$res_str .= "No values found from LocaleTime parsing.";
                $res_str .= "\tError : '" . intl_get_error_message() . "'";
            }
        }
    }
    return $res_str;
}
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $dateFormat = is_int($options['format']) ? $options['format'] : self::DEFAULT_FORMAT;
     $timeFormat = \IntlDateFormatter::NONE;
     $calendar = \IntlDateFormatter::GREGORIAN;
     $pattern = is_string($options['format']) ? $options['format'] : null;
     if (!in_array($dateFormat, self::$acceptedFormats, true)) {
         throw new InvalidOptionsException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.');
     }
     if (null !== $pattern && (false === strpos($pattern, 'y') || false === strpos($pattern, 'M') || false === strpos($pattern, 'd'))) {
         throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern));
     }
     if ('single_text' === $options['widget']) {
         $builder->addViewTransformer(new DateTimeToLocalizedStringTransformer($options['model_timezone'], $options['view_timezone'], $dateFormat, $timeFormat, $calendar, $pattern));
     } else {
         $yearOptions = $monthOptions = $dayOptions = array('error_bubbling' => true);
         $formatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, null, $calendar, $pattern);
         // new \intlDateFormatter may return null instead of false in case of failure, see https://bugs.php.net/bug.php?id=66323
         if (!$formatter) {
             throw new InvalidOptionsException(intl_get_error_message(), intl_get_error_code());
         }
         $formatter->setLenient(false);
         if ('choice' === $options['widget']) {
             // Only pass a subset of the options to children
             $yearOptions['choices'] = $this->formatTimestamps($formatter, '/y+/', $this->listYears($options['years']));
             $yearOptions['choices_as_values'] = true;
             $yearOptions['placeholder'] = $options['placeholder']['year'];
             $yearOptions['choice_translation_domain'] = $options['choice_translation_domain']['year'];
             $monthOptions['choices'] = $this->formatTimestamps($formatter, '/[M|L]+/', $this->listMonths($options['months']));
             $monthOptions['choices_as_values'] = true;
             $monthOptions['placeholder'] = $options['placeholder']['month'];
             $monthOptions['choice_translation_domain'] = $options['choice_translation_domain']['month'];
             $dayOptions['choices'] = $this->formatTimestamps($formatter, '/d+/', $this->listDays($options['days']));
             $dayOptions['choices_as_values'] = true;
             $dayOptions['placeholder'] = $options['placeholder']['day'];
             $dayOptions['choice_translation_domain'] = $options['choice_translation_domain']['day'];
         }
         // Append generic carry-along options
         foreach (array('required', 'translation_domain') as $passOpt) {
             $yearOptions[$passOpt] = $monthOptions[$passOpt] = $dayOptions[$passOpt] = $options[$passOpt];
         }
         $builder->add('year', self::$widgets[$options['widget']], $yearOptions)->add('month', self::$widgets[$options['widget']], $monthOptions)->add('day', self::$widgets[$options['widget']], $dayOptions)->addViewTransformer(new DateTimeToArrayTransformer($options['model_timezone'], $options['view_timezone'], array('year', 'month', 'day')))->setAttribute('formatter', $formatter);
     }
     if ('string' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToStringTransformer($options['model_timezone'], $options['model_timezone'], 'Y-m-d')));
     } elseif ('timestamp' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToTimestampTransformer($options['model_timezone'], $options['model_timezone'])));
     } elseif ('array' === $options['input']) {
         $builder->addModelTransformer(new ReversedTransformer(new DateTimeToArrayTransformer($options['model_timezone'], $options['model_timezone'], array('year', 'month', 'day'))));
     }
 }
 /**
  * Transforms a localized date string/array into a normalized date.
  *
  * @param  string|array $value Localized date string/array
  * @return DateTime Normalized date
  */
 public function reverseTransform($value)
 {
     $inputTimezone = $this->getOption('input_timezone');
     if (!is_string($value)) {
         throw new \InvalidArgumentException(sprintf('Expected argument of type string, %s given', gettype($value)));
     }
     $timestamp = $this->getIntlDateFormatter()->parse($value);
     if (intl_get_error_code() != 0) {
         throw new TransformationFailedException(intl_get_error_message());
     }
     // read timestamp into DateTime object - the formatter delivers in UTC
     $dateTime = new \DateTime(sprintf('@%s UTC', $timestamp));
     if ($inputTimezone != 'UTC') {
         $dateTime->setTimezone(new \DateTimeZone($inputTimezone));
     }
     return $dateTime;
 }
Example #8
0
function ut_main()
{
    $res_str = '';
    $forms = array(Normalizer::FORM_C, Normalizer::FORM_D, Normalizer::FORM_KC, Normalizer::FORM_KD, Normalizer::NONE);
    $forms_str = array(Normalizer::FORM_C => 'UNORM_FORM_C', Normalizer::FORM_D => 'UNORM_FORM_D', Normalizer::FORM_KC => 'UNORM_FORM_KC', Normalizer::FORM_KD => 'UNORM_FORM_KD', Normalizer::NONE => 'UNORM_NONE');
    /* just make sure all the form constants are defined as in the api spec */
    if (Normalizer::FORM_C != Normalizer::NFC || Normalizer::FORM_D != Normalizer::NFD || Normalizer::FORM_KC != Normalizer::NFKC || Normalizer::FORM_KD != Normalizer::NFKD || Normalizer::NONE == Normalizer::FORM_C) {
        $res_str .= "Invalid normalization form declarations!\n";
    }
    $char_a_diaeresis = "ä";
    // 'LATIN SMALL LETTER A WITH DIAERESIS' (U+00E4)
    $char_a_ring = "å";
    // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5)
    $char_o_diaeresis = "ö";
    // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6)
    $char_angstrom_sign = "Å";
    // 'ANGSTROM SIGN' (U+212B)
    $char_A_ring = "Å";
    // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
    $char_ohm_sign = "Ω";
    // 'OHM SIGN' (U+2126)
    $char_omega = "Ω";
    // 'GREEK CAPITAL LETTER OMEGA' (U+03A9)
    $char_combining_ring_above = "̊";
    // 'COMBINING RING ABOVE' (U+030A)
    $char_fi_ligature = "fi";
    // 'LATIN SMALL LIGATURE FI' (U+FB01)
    $char_long_s_dot = "ẛ";
    // 'LATIN SMALL LETTER LONG S WITH DOT ABOVE' (U+1E9B)
    $strs = array('ABC', $char_a_diaeresis . '||' . $char_a_ring . '||' . $char_o_diaeresis, $char_angstrom_sign . '||' . $char_A_ring . '||' . 'A' . $char_combining_ring_above, $char_ohm_sign . '||' . $char_omega, $char_fi_ligature, $char_long_s_dot);
    foreach ($forms as $form) {
        foreach ($strs as $str) {
            $str_norm = ut_norm_normalize($str, $form);
            $error_code = intl_get_error_code();
            $error_message = intl_get_error_message();
            $str_hex = urlencode($str);
            $str_norm_hex = urlencode($str_norm);
            $res_str .= "'{$str_hex}' normalized to form '{$forms_str[$form]}' is '{$str_norm_hex}'" . "\terror info: '{$error_message}' ({$error_code})\n" . "";
            $is_norm = ut_norm_is_normalized($str, $form);
            $error_code = intl_get_error_code();
            $error_message = intl_get_error_message();
            $res_str .= "\t\tis in form '{$forms_str[$form]}'? = " . ($is_norm ? "yes" : "no") . "\terror info: '{$error_message}' ({$error_code})\n" . "";
        }
    }
    return $res_str;
}
Example #9
0
function ut_main()
{
    $locales = array('en_US' => "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", 'ru_UA' => "{0,number,integer} мавп на {1,number,integer} деревах це {2,number} мавпи на кожному деревi", 'de' => "{0,number,integer} Affen über {1,number,integer} Bäume um {2,number} Affen pro Baum", 'en_UK' => "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", 'root' => '{0,whatever} would not work!', 'fr' => 'C\'est {0,number,integer}');
    $results = array('en_US' => "4,560 monkeys on 123 trees make 37.073 monkeys per tree", 'ru_UA' => "4 560 мавп на 123 деревах це 37,073 мавпи на кожному деревi", 'de' => "4.560 Affen über 123 Bäume um 37,073 Affen pro Baum", 'en_UK' => "4,560 monkeys on 123 trees make 37.073 monkeys per tree", 'root' => "4,560 monkeys on 123 trees make 37.073 monkeys per tree", 'fr' => "C'est 42");
    $str_res = '';
    foreach ($locales as $locale => $pattern) {
        $str_res .= "\nLocale is: {$locale}\n";
        $fmt = ut_msgfmt_create($locale, $pattern);
        if (!$fmt) {
            $str_res .= dump(intl_get_error_message()) . "\n";
            continue;
        }
        $str_res .= dump(ut_msgfmt_parse($fmt, $results[$locale])) . "\n";
        $str_res .= dump(ut_msgfmt_parse_message($locale, $pattern, $results[$locale])) . "\n";
    }
    return $str_res;
}
Example #10
0
function ut_main()
{
    $locales = array('en_US' => "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", 'ru_UA' => "{0,number,integer} мавп на {1,number,integer} деревах це {2,number} мавпи на кожному деревi", 'de' => "{0,number,integer} Affen über {1,number,integer} Bäume um {2,number} Affen pro Baum", 'en_UK' => "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree", 'root' => '{0,whatever} would not work!', 'fr' => "C'est la vie!");
    $str_res = '';
    $m = 4560;
    $t = 123;
    foreach ($locales as $locale => $pattern) {
        $str_res .= "\nLocale is: {$locale}\n";
        $fmt = ut_msgfmt_create($locale, $pattern);
        if (!$fmt) {
            $str_res .= dump(intl_get_error_message()) . "\n";
            continue;
        }
        $str_res .= dump(ut_msgfmt_format($fmt, array($m, $t, $m / $t))) . "\n";
        $str_res .= dump(ut_msgfmt_format_message($locale, $pattern, array($m, $t, $m / $t))) . "\n";
    }
    return $str_res;
}
Example #11
0
function ut_main()
{
    $locale_arr = array('en_US_CA');
    $datetype_arr = array(IntlDateFormatter::FULL, IntlDateFormatter::LONG, IntlDateFormatter::MEDIUM, IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
    $res_str = '';
    $text_arr = array(array("Sunday, September 18, 2039 4:06:40 PM PT", IntlDateFormatter::FULL, IntlDateFormatter::FULL), array("Wednesday, December 17, 1969 6:40:00 PM PT", IntlDateFormatter::FULL, IntlDateFormatter::FULL), array("Thursday, December 18, 1969 8:49:59 PM PST", IntlDateFormatter::FULL, IntlDateFormatter::FULL), array("December 18, 1969 8:49:59 AM PST", IntlDateFormatter::LONG, IntlDateFormatter::FULL), array("12/18/69 8:49 AM", IntlDateFormatter::SHORT, IntlDateFormatter::SHORT), array("19691218 08:49 AM", IntlDateFormatter::SHORT, IntlDateFormatter::SHORT), array("Sunday, September 18, 2039 4:06:40 PM PT", IntlDateFormatter::FULL, IntlDateFormatter::NONE), array("Sunday, September 18, 2039 4:06:40 PM PT", IntlDateFormatter::FULL, IntlDateFormatter::SHORT), array("December 18, 1969 8:49:59 AM PST", IntlDateFormatter::LONG, IntlDateFormatter::NONE), array("December 18, 1969 8:49:59 AM PST", IntlDateFormatter::LONG, IntlDateFormatter::SHORT), array("12/18/69 8:49 AM", IntlDateFormatter::SHORT, IntlDateFormatter::LONG), array("19691218 08:49 AM", IntlDateFormatter::SHORT, IntlDateFormatter::LONG));
    foreach ($text_arr as $text_entry) {
        $fmt = ut_datefmt_create('en_US_CA', $text_entry[1], $text_entry[2]);
        $parse_pos = 0;
        $parsed = ut_datefmt_parse($fmt, $text_entry[0], $parse_pos);
        $res_str .= "\nInput text : {$text_entry[0]} ; DF = {$text_entry[1]}; TF = {$text_entry[2]}";
        if (intl_get_error_code() != U_ZERO_ERROR) {
            $res_str .= "\nError : " . intl_get_error_message();
        }
        $res_str .= "\nParsed: {$parsed}; parse_pos : {$parse_pos}\n";
    }
    return $res_str;
}
Example #12
0
function ut_main()
{
    $res_str = '';
    $locales = array('EN-US-ODESSA', 'UK_UA_ODESSA', 'uk-ua_CALIFORNIA@currency=;currency=GRN', '', 'root', 'uk@currency=EURO', '1234567891113151719212325272931333537394143454749515357596163656769717375777981838587899193959799');
    foreach ($locales as $locale) {
        // Create Collator with the current locale.
        $coll = ut_coll_create($locale);
        if (!is_object($coll)) {
            $res_str .= "Error creating collator with '{$locale}' locale: " . intl_get_error_message() . "\n";
            continue;
        }
        // Get the requested, valid and actual locales.
        $vloc = ut_coll_get_locale($coll, Locale::VALID_LOCALE);
        $aloc = ut_coll_get_locale($coll, Locale::ACTUAL_LOCALE);
        // Show them.
        $res_str .= "Locale: '{$locale}'\n" . "  ULOC_REQUESTED_LOCALE = '{$locale}'\n" . "  ULOC_VALID_LOCALE     = '{$vloc}'\n" . "  ULOC_ACTUAL_LOCALE    = '{$aloc}'\n";
    }
    return $res_str;
}
 /**
  * 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;
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 public function format($value, array $options = array())
 {
     if (null === $value) {
         return $options['null_value'];
     }
     if (!$value instanceof \DateTime) {
         throw FormatterException::invalidType($this, $value, 'DateTime instance');
     }
     $dateTime = clone $value;
     if ('UTC' !== $options['time_zone']) {
         $dateTime->setTimezone(new \DateTimeZone('UTC'));
     }
     $formatter = new \IntlDateFormatter(\Locale::getDefault(), $options['date_format'], $options['time_format'], $options['time_zone'], $options['calendar'], $options['pattern']);
     $formatter->setLenient(false);
     $value = $formatter->format((int) $dateTime->format('U'));
     if (intl_is_failure(intl_get_error_code())) {
         throw FormatterException::intlError($this, intl_get_error_message());
     }
     $value = preg_replace('~GMT\\+00:00$~', 'GMT', $value);
     return $value;
 }
Example #15
0
function ut_main()
{
    $loc_parts_arr1 = array(Locale::LANG_TAG => 'sl', Locale::SCRIPT_TAG => 'Latn', Locale::REGION_TAG => 'IT');
    $loc_parts_arr2 = array(Locale::LANG_TAG => 'de', Locale::REGION_TAG => 'DE');
    $loc_parts_arr3 = array(Locale::LANG_TAG => 'hi');
    $loc_parts_arr4 = array(Locale::LANG_TAG => 'zh', Locale::SCRIPT_TAG => 'Hans', Locale::REGION_TAG => 'CN');
    $loc_parts_arr5 = array(Locale::LANG_TAG => 'es', Locale::SCRIPT_TAG => 'Hans', Locale::REGION_TAG => 'CN');
    $loc_parts_arr6 = array(Locale::LANG_TAG => 'en', Locale::SCRIPT_TAG => 'Hans', Locale::REGION_TAG => 'CN', Locale::VARIANT_TAG . '14' => 'rozaj', 'variant1' => 'nedis');
    $loc_parts_arr7 = array(Locale::LANG_TAG => 'en', Locale::SCRIPT_TAG => 'Hans', Locale::REGION_TAG => 'CN', 'variant14' => 'rozaj', 'variant1' => 'nedis', 'extlang0' => 'lng', 'extlang1' => 'ing');
    $loc_parts_arr8 = array(Locale::LANG_TAG => 'en', Locale::SCRIPT_TAG => 'Hans', Locale::REGION_TAG => 'CN', 'variant14' => 'rozaj', 'variant1' => 'nedis', 'extlang0' => 'lng', 'extlang1' => 'ing', 'private7' => 'prv1', 'private9' => 'prv2');
    $loc_parts_arr9 = array(Locale::REGION_TAG => 'DE');
    $loc_parts_arr10 = array(Locale::LANG_TAG => 45, Locale::REGION_TAG => false, Locale::SCRIPT_TAG => 15);
    $loc_parts_arr11 = array(Locale::LANG_TAG => 'de', Locale::REGION_TAG => 'DE', 'private0' => 13, 'variant1' => array(), 'extlang2' => false);
    $loc_parts_arr12 = array(Locale::LANG_TAG => 'en', Locale::SCRIPT_TAG => 'Hans', Locale::REGION_TAG => 'CN', Locale::VARIANT_TAG => array('nedis', 'rozaj'), Locale::PRIVATE_TAG => array('prv1', 'prv2'), Locale::EXTLANG_TAG => array('lng', 'ing'));
    $loc_parts_arr = array('loc1' => $loc_parts_arr1, 'loc2' => $loc_parts_arr2, 'loc3' => $loc_parts_arr3, 'loc4' => $loc_parts_arr4, 'loc5' => $loc_parts_arr5, 'loc6' => $loc_parts_arr6, 'loc7' => $loc_parts_arr7, 'loc8' => $loc_parts_arr8, 'loc9' => $loc_parts_arr9, 'loc10' => $loc_parts_arr10, 'loc11' => $loc_parts_arr11, 'loc12' => $loc_parts_arr12);
    error_reporting(E_ERROR);
    $cnt = 0;
    $res_str = '';
    foreach ($loc_parts_arr as $key => $value) {
        $res_str .= "\n------------";
        $res_str .= "\nInput Array name is : loc" . ++$cnt;
        /*	
        		foreach($value as $valKey => $valValue ){
        			$res_str .=  $valKey ."->".$valValue."  " ;
        		}
        */
        $locale = ut_loc_locale_compose($value);
        $res_str .= "\n\nComposed Locale: ";
        if ($locale) {
            $res_str .= "{$locale}";
        } else {
            $res_str .= "No values found from Locale compose due to the following error:\n";
            $res_str .= intl_get_error_message();
        }
    }
    $res_str .= "\n------------";
    $res_str .= "\n";
    return $res_str;
}
 /**
  * Creates date time object from date string
  *
  * @param string $dateString
  * @param string|null $timeZone
  * @param string $format
  * @throws \Exception
  * @return \DateTime
  */
 private function createDateTime($dateString, $timeZone = null, $format = 'yyyy-MM-dd')
 {
     $pattern = $format ? $format : null;
     if (!$timeZone) {
         $timeZone = date_default_timezone_get();
     }
     $calendar = \IntlDateFormatter::GREGORIAN;
     $intlDateFormatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, $timeZone, $calendar, $pattern);
     $intlDateFormatter->setLenient(false);
     $timestamp = $intlDateFormatter->parse($dateString);
     if (intl_get_error_code() != 0) {
         throw new \Exception(intl_get_error_message());
     }
     // read timestamp into DateTime object - the formatter delivers in UTC
     $dateTime = new \DateTime(sprintf('@%s UTC', $timestamp));
     if ('UTC' !== $timeZone) {
         try {
             $dateTime->setTimezone(new \DateTimeZone($timeZone));
         } catch (\Exception $e) {
             throw new \Exception($e->getMessage(), $e->getCode(), $e);
         }
     }
     return $dateTime;
 }
Example #17
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;
     }
 }
 private function formatDateTimeValue($value, $format, $type)
 {
     $timeZone = $this->timeZone;
     // avoid time zone conversion for date-only values
     if ($type === 'date') {
         list($timestamp, $hasTimeInfo) = $this->normalizeDatetimeValue($value, true);
         if (!$hasTimeInfo) {
             $timeZone = $this->defaultTimeZone;
         }
     } else {
         $timestamp = $this->normalizeDatetimeValue($value);
     }
     if ($timestamp === null) {
         return $this->nullDisplay;
     }
     // intl does not work with dates >=2038 or <=1901 on 32bit machines, fall back to PHP
     $year = $timestamp->format('Y');
     if ($this->_intlLoaded && !(PHP_INT_SIZE == 4 && ($year <= 1901 || $year >= 2038))) {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
         }
         if (isset($this->_dateFormats[$format])) {
             if ($type === 'date') {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $timeZone);
             } elseif ($type === 'time') {
                 $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $timeZone);
             } else {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $timeZone);
             }
         } else {
             $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $timeZone, null, $format);
         }
         if ($formatter === null) {
             throw new InvalidConfigException(intl_get_error_message());
         }
         // make IntlDateFormatter work with DateTimeImmutable
         if ($timestamp instanceof \DateTimeImmutable) {
             $timestamp = new DateTime($timestamp->format(DateTime::ISO8601), $timestamp->getTimezone());
         }
         return $formatter->format($timestamp);
     } else {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = substr($format, 4);
         } else {
             $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
         }
         if ($timeZone != null) {
             if ($timestamp instanceof \DateTimeImmutable) {
                 $timestamp = $timestamp->setTimezone(new DateTimeZone($timeZone));
             } else {
                 $timestamp->setTimezone(new DateTimeZone($timeZone));
             }
         }
         return $timestamp->format($format);
     }
 }
 /**
  * @dataProvider parseProvider
  */
 public function testParseIntl($pattern, $value, $expected, $errorCode = 0, $errorMessage = 'U_ZERO_ERROR')
 {
     $this->skipIfIntlExtensionIsNotLoaded();
     $formatter = $this->createIntlFormatter($pattern);
     $this->assertSame($expected, $formatter->parse($value));
     $this->assertSame($errorMessage, intl_get_error_message());
     $this->assertSame($errorCode, intl_get_error_code());
     $this->assertSame($errorCode != 0, intl_is_failure(intl_get_error_code()));
 }
 /**
  * Returns a preconfigured IntlDateFormatter instance.
  *
  * @param bool $ignoreTimezone Use UTC regardless of the configured timezone.
  *
  * @return \IntlDateFormatter
  *
  * @throws TransformationFailedException in case the date formatter can not be constructed.
  */
 protected function getIntlDateFormatter($ignoreTimezone = false)
 {
     $dateFormat = $this->dateFormat;
     $timeFormat = $this->timeFormat;
     $timezone = $ignoreTimezone ? 'UTC' : $this->outputTimezone;
     $calendar = $this->calendar;
     $pattern = $this->pattern;
     $intlDateFormatter = new \IntlDateFormatter(\Locale::getDefault(), $dateFormat, $timeFormat, $timezone, $calendar, $pattern);
     // new \intlDateFormatter may return null instead of false in case of failure, see https://bugs.php.net/bug.php?id=66323
     if (!$intlDateFormatter) {
         throw new TransformationFailedException(intl_get_error_message(), intl_get_error_code());
     }
     $intlDateFormatter->setLenient(false);
     return $intlDateFormatter;
 }
Example #21
0
 /**
  * @param integer|string|DateTime $value 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](http://php.net/manual/en/datetime.formats.php).
  *   The timestamp is assumed to be in UTC unless a timezone is explicitly given.
  * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
  *
  * @param string $format the format used to convert the value into a date string.
  * @param string $type 'date', 'time', or 'datetime'.
  * @throws InvalidConfigException if the date format is invalid.
  * @return string the formatted result.
  */
 private function formatDateTimeValue($value, $format, $type)
 {
     $timestamp = $this->normalizeDatetimeValue($value);
     if ($timestamp === null) {
         return $this->nullDisplay;
     }
     if ($this->_intlLoaded) {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = FormatConverter::convertDatePhpToIcu(substr($format, 4));
         }
         if (isset($this->_dateFormats[$format])) {
             if ($type === 'date') {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], IntlDateFormatter::NONE, $this->timeZone);
             } elseif ($type === 'time') {
                 $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, $this->_dateFormats[$format], $this->timeZone);
             } else {
                 $formatter = new IntlDateFormatter($this->locale, $this->_dateFormats[$format], $this->_dateFormats[$format], $this->timeZone);
             }
         } else {
             $formatter = new IntlDateFormatter($this->locale, IntlDateFormatter::NONE, IntlDateFormatter::NONE, $this->timeZone, null, $format);
         }
         if ($formatter === null) {
             throw new InvalidConfigException(intl_get_error_message());
         }
         return $formatter->format($timestamp);
     } else {
         if (strncmp($format, 'php:', 4) === 0) {
             $format = substr($format, 4);
         } else {
             $format = FormatConverter::convertDateIcuToPhp($format, $type, $this->locale);
         }
         if ($this->timeZone != null) {
             $timestamp->setTimezone(new DateTimeZone($this->timeZone));
         }
         return $timestamp->format($format);
     }
 }
Example #22
0
 protected function getIntlErrorMessage()
 {
     return intl_get_error_message();
 }
Example #23
0
 /**
  * @return NumberFormatter
  * @throws Exception\RuntimeException
  */
 public function getFormatter()
 {
     if ($this->formatter === null) {
         $formatter = NumberFormatter::create($this->getLocale(), $this->getStyle());
         if (!$formatter) {
             throw new Exception\RuntimeException('Can not create NumberFormatter instance; ' . intl_get_error_message());
         }
         $this->formatter = $formatter;
     }
     return $this->formatter;
 }
Example #24
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;
     }
 }
 /**
  * Transforms a localized date string/array into a normalized date.
  *
  * @param string|array $value Localized date string/array
  *
  * @return DateTime Normalized date
  *
  * @throws UnexpectedTypeException if the given value is not a string
  * @throws TransformationFailedException if the date could not be parsed
  * @throws TransformationFailedException if the input timezone is not supported
  */
 public function reverseTransform($value)
 {
     if (!is_string($value)) {
         throw new UnexpectedTypeException($value, 'string');
     }
     if ('' === $value) {
         return null;
     }
     $timestamp = $this->getIntlDateFormatter()->parse($value);
     if (intl_get_error_code() != 0) {
         throw new TransformationFailedException(intl_get_error_message());
     }
     // read timestamp into DateTime object - the formatter delivers in UTC
     $dateTime = new \DateTime(sprintf('@%s UTC', $timestamp));
     if ('UTC' !== $this->inputTimezone) {
         try {
             $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
         } catch (\Exception $e) {
             throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
         }
     }
     return $dateTime;
 }
Example #26
0
    /**
     * Ensures that a collator is available and created
     *
     * @return bool Returns true if collation is available and ready
     */
    protected static function ensure_collator_available() {
        global $CFG;

        $locale = get_string('locale', 'langconfig');
        if (is_null(self::$collator) || $locale != self::$locale) {
            self::$collator = false;
            self::$locale = $locale;
            if (class_exists('Collator', false)) {
                $collator = new Collator($locale);
                if (!empty($collator) && $collator instanceof Collator) {
                    // Check for non fatal error messages. This has to be done immediately
                    // after instantiation as any further calls to collation will cause
                    // it to reset to 0 again (or another error code if one occurred)
                    $errorcode = $collator->getErrorCode();
                    $errormessage = $collator->getErrorMessage();
                    // Check for an error code, 0 means no error occurred
                    if ($errorcode !== 0) {
                        // Get the actual locale being used, e.g. en, he, zh
                        $localeinuse = $collator->getLocale(Locale::ACTUAL_LOCALE);
                        // Check for the common fallback warning error codes. If this occurred
                        // there is normally little to worry about:
                        // - U_USING_DEFAULT_WARNING (127)  - default fallback locale used (pt => UCA)
                        // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
                        // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
                        if ($errorcode === -127 || $errorcode === -128) {
                            // Check if the locale in use is UCA default one ('root') or
                            // if it is anything like the locale we asked for
                            if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
                                // The locale we asked for is completely different to the locale
                                // we have received, let the user know via debugging
                                debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage .
                                    '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
                            } else {
                                // Nothing to do here, this is expected!
                                // The Moodle locale setting isn't what the collator expected but
                                // it is smart enough to match the first characters of our locale
                                // to find the correct locale or to use UCA collation
                            }
                        } else {
                            // We've recieved some other sort of non fatal warning - let the
                            // user know about it via debugging.
                            debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage .
                                '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
                        }
                    }
                    // Store the collator object now that we can be sure it is in a workable condition
                    self::$collator = $collator;
                } else {
                    // Fatal error while trying to instantiate the collator... something went wrong
                    debugging('Error instantiating collator for locale: "' . $locale . '", with error [' .
                        intl_get_error_code() . '] ' . intl_get_error_message($collator));
                }
            }
        }
        return (self::$collator instanceof Collator);
    }
 /**
  * @dataProvider parseProvider
  */
 public function testParseIntl($value, $expected, $message = '')
 {
     $this->skipIfIntlExtensionIsNotLoaded();
     $this->skipIfICUVersionIsTooOld();
     $formatter = $this->getIntlFormatterWithDecimalStyle();
     $parsedValue = $formatter->parse($value, \NumberFormatter::TYPE_DOUBLE);
     $this->assertSame($expected, $parsedValue, $message);
     if ($expected === false) {
         $errorCode = StubIntl::U_PARSE_ERROR;
         $errorMessage = 'Number parsing failed: U_PARSE_ERROR';
     } else {
         $errorCode = StubIntl::U_ZERO_ERROR;
         $errorMessage = 'U_ZERO_ERROR';
     }
     $this->assertSame($errorMessage, intl_get_error_message());
     $this->assertSame($errorCode, intl_get_error_code());
     $this->assertSame($errorCode > 0, intl_is_failure(intl_get_error_code()));
     $this->assertSame($errorMessage, $formatter->getErrorMessage());
     $this->assertSame($errorCode, $formatter->getErrorCode());
     $this->assertSame($errorCode > 0, intl_is_failure($formatter->getErrorCode()));
 }
 /**
  * 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;
     }
 }
Example #29
0
 /**
  * Сравнение строк
  *
  * @param   string|null    $s1
  * @param   string|null    $s2
  * @param   string         $locale   For example, 'en_CA', 'ru_RU'
  * @return  int|bool|null  Returns FALSE if error occurred
  *                         Returns < 0 if $s1 is less than $s2;
  *                                 > 0 if $s1 is greater than $s2;
  *                                 0 if they are equal.
  */
 public static function strcmp($s1, $s2, $locale = '')
 {
     if (!ReflectionTypeHint::isValid()) {
         return false;
     }
     if (is_null($s1) || is_null($s2)) {
         return null;
     }
     if (!function_exists('collator_create')) {
         return strcmp($s1, $s2);
     }
     # PHP 5 >= 5.3.0, PECL intl >= 1.0.0
     # If empty string ("") or "root" are passed, UCA rules will be used.
     $c = new Collator($locale);
     if (!$c) {
         # Returns an "empty" object on error. You can use intl_get_error_code() and/or intl_get_error_message() to know what happened.
         trigger_error(intl_get_error_message(), E_USER_WARNING);
         return false;
     }
     return $c->compare($s1, $s2);
 }
Example #30
0
function err($fmt)
{
    if (!$fmt) {
        echo var_export(intl_get_error_message(), true) . "\n";
    }
}