Пример #1
0
 /**
  * @covers ::format
  */
 public function testExceptionOnInvalidCategory()
 {
     if (IntlHelper::getIcuVersion() < 52) {
         $this->markTestSkipped('Categories are only used as of ICU version 52');
     }
     $this->setExpectedException('UnexpectedValueException', 'Invalid category provided: "foobar"');
     $formatter = new UnitFormatter('en-US');
     $formatter->format(1, 'foobar', 'hour', 'wide');
 }
Пример #2
0
 /**
  * @param  int|float|string $number
  * @param  string           $category
  * @param  string           $unit
  * @param  string           $width
  * @return string
  * @throws UnexpectedValueException
  */
 public function format($number, $category, $unit, $width)
 {
     if (!isset(static::$widthMap[$width])) {
         throw new UnexpectedValueException(sprintf('Invalid width provided: "%s", must be either wide, short or narrow', $width));
     }
     if (IntlHelper::getIcuVersion() >= 52) {
         $categoryBundle = $this->resourceBundle->get(static::$widthMap[$width])->get($category);
         if ($categoryBundle === null) {
             throw new UnexpectedValueException(sprintf('Invalid category provided: "%s"', $category));
         }
         $unitBundle = $categoryBundle->get($unit);
     } else {
         $unitBundle = $this->resourceBundle->get(static::$widthMap[$width])->get($unit);
     }
     if ($unitBundle === null) {
         throw new UnexpectedValueException(sprintf('Invalid unit provided: "%s"', $unit));
     }
     $unitFormats = [];
     foreach ($unitBundle as $numberCategory => $format) {
         $unitFormats[] = sprintf('%s{%s}', $numberCategory, str_replace('{0}', '{0, number}', $format));
     }
     $this->messageFormatter->setPattern(sprintf('{0, plural, %s}', implode('', $unitFormats)));
     return $this->messageFormatter->format([$number]);
 }