1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace hiqdev\php\units\yii2\formatters; |
4
|
|
|
|
5
|
|
|
use hiqdev\php\units\FormatterInterface; |
6
|
|
|
use hiqdev\php\units\formatters\SimpleFormatter; |
7
|
|
|
use hiqdev\php\units\Quantity; |
8
|
|
|
use hiqdev\php\units\Unit; |
9
|
|
|
use Yii; |
10
|
|
|
use yii\i18n\Formatter; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class IntlFormatter |
14
|
|
|
* |
15
|
|
|
* @author Dmytro Naumenko <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class IntlFormatter implements FormatterInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var SimpleFormatter |
21
|
|
|
*/ |
22
|
|
|
protected $simpleFormatter; |
23
|
|
|
/** |
24
|
|
|
* @var Formatter |
25
|
|
|
*/ |
26
|
|
|
private $formatter; |
27
|
|
|
|
28
|
|
|
public function __construct(Formatter $formatter) |
29
|
|
|
{ |
30
|
|
|
$this->formatter = $formatter; |
31
|
|
|
$this->simpleFormatter = new SimpleFormatter(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param Quantity $quantity |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
|
|
public function format(Quantity $quantity): string |
39
|
|
|
{ |
40
|
|
|
$format = $this->formatter; |
41
|
|
|
$format->sizeFormatBase = 1000; |
42
|
|
|
|
43
|
|
|
// TODO: split to different classes |
44
|
|
|
switch ($quantity->getUnit()->getMeasure()) { |
45
|
|
|
case 'bit': |
46
|
|
|
return Yii::t('hiqdev.units', '{quantity, number} {unit}', [ |
47
|
|
|
'quantity' => $quantity->getQuantity(), |
48
|
|
|
'unit' => (function (string $unitName) { |
49
|
|
|
switch ($unitName) { |
50
|
|
|
case 'b': return Yii::t('hiqdev.units', 'B'); |
51
|
|
|
case 'kb': return Yii::t('hiqdev.units', 'kB'); |
52
|
|
|
case 'mb': return Yii::t('hiqdev.units', 'MB'); |
53
|
|
|
case 'gb': return Yii::t('hiqdev.units', 'GB'); |
54
|
|
|
case 'tb': return Yii::t('hiqdev.units', 'TB'); |
55
|
|
|
case 'pb': return Yii::t('hiqdev.units', 'PB'); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return Yii::t('hiqdev.units', ''); |
59
|
|
|
})($quantity->getUnit()->getName()) |
60
|
|
|
]); |
61
|
|
|
case 'bps': |
62
|
|
|
return Yii::t('hiqdev.units', '{quantity, number} {unit}', [ |
63
|
|
|
'quantity' => $quantity->getQuantity(), |
64
|
|
|
'unit' => (function (string $unitName) { |
65
|
|
|
switch ($unitName) { |
66
|
|
|
case 'bps': return Yii::t('hiqdev.units', 'b/s'); |
67
|
|
|
case 'kbps': return Yii::t('hiqdev.units', 'Kb/s'); |
68
|
|
|
case 'mbps': return Yii::t('hiqdev.units', 'Mb/s'); |
69
|
|
|
case 'gbps': return Yii::t('hiqdev.units', 'Gb/s'); |
70
|
|
|
} |
71
|
|
|
return Yii::t('hiqdev.units', ''); |
72
|
|
|
})($quantity->getUnit()->getName()) |
73
|
|
|
]); |
74
|
|
|
case 'item': |
75
|
|
|
return Yii::t('hiqdev.units', '{quantity, plural, one{# item} other{# items}}', ['quantity' => $quantity->getQuantity()]); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $this->simpleFormatter->format($quantity); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|