Example #1
0
 /**
  * Format a string depending on a quantity.
  *
  * See the class documentation for defining `$format`.
  *
  * @param string $format
  * @param string $quantity
  *
  * @return mixed
  */
 public static function format($format, $quantity)
 {
     $quantity = Numeric::ensure($quantity);
     $callback = function ($matches) use($quantity) {
         // Get available choices
         $choices = preg_split('/\\|/', $matches[2]);
         // Assume plural
         $choice = 0;
         // Choose singular
         if ($quantity === 1.0 || $quantity === 1) {
             $choice = 1;
         }
         // Choose zero if it's defined, otherwise keep using plural format
         if (($quantity === 0 || $quantity === 0.0) && isset($choices[2])) {
             $choice = 2;
         }
         return Dot::get($choices, $choice, '');
     };
     $pattern = '/(?<!\\\\)(\\((.+?(?<!\\\\))\\))/';
     $out = preg_replace_callback($pattern, $callback, $format);
     $out = sprintf($out, $quantity);
     return $out;
 }
Example #2
0
 /**
  * Format a quantity of bytes for human consumption.
  *
  * @param int $bytes
  *
  * @return string
  */
 public function format($bytes)
 {
     $bytes = Numeric::ensure($bytes);
     if (is_float($bytes) && $bytes > 0.0 && $bytes < 1.0) {
         throw new \InvalidArgumentException('Floats smaller than one can not be formatted.');
     }
     // 0 bytes won't work with log(), so set defaults for this case
     $exponent = 0;
     $normBytes = 0;
     if ($bytes !== 0) {
         $exponent = log(abs($bytes), $this->base);
         $normBytes = pow($this->base, $exponent - floor($exponent));
         // Make bytes negative again if needed
         $normBytes *= $bytes >= 0 ? 1 : -1;
     }
     $suffix = self::$suffixes[$this->suffix][$exponent];
     $number = number_format($normBytes, $this->precision, '.', '');
     $number = $this->trimPrecision($number);
     $suffix = Quantity::format($suffix, $number);
     return sprintf('%s %s', $number, $suffix);
 }
Example #3
0
 /**
  * @dataProvider ensureFloatProvider
  *
  * @param float $expected
  * @param mixed $value
  *
  * @covers \nochso\Omni\Numeric::ensureFloat
  */
 public function testEnsureFloat($expected, $value)
 {
     $actual = Numeric::ensureFloat($value);
     $this->assertInternalType('float', $actual);
     $this->assertSame($expected, $actual);
 }
Example #4
0
 /**
  * @param int|\DateInterval $duration
  *
  * @return int
  */
 private function ensureSeconds($duration)
 {
     if ($duration instanceof \DateInterval) {
         $d1 = new \DateTime('@0');
         return $d1->add($duration)->getTimestamp();
     }
     return Numeric::ensure($duration);
 }