jbzoo / simpletypes
通用的PHP库,用于转换任何值和度量
7.0.1
2024-01-28 12:22 UTC
Requires
- php: ^8.1
- jbzoo/utils: ^7.1
Requires (Dev)
- jbzoo/toolbox-dev: ^7.1
README
通用的PHP库,用于转换任何值和度量 - 货币、重量、货币转换器、长度以及你想要的任何东西 ;)
安装
composer require jbzoo/simpletypes
示例
use JBZoo\SimpleTypes\Config; use JBZoo\SimpleTypes\Money; use JBZoo\SimpleTypes\ConfigMoney; // Set config object for all Money objects as default Config::registerDefault('money', new ConfigMoney()); // Create any object, some different ways $money = new Money('10 eur'); $weight = new Weight('1000'); // Gram is default in the ConfigWeight class $length = new Length('500 km'); $money = new Money('100500 usd', new ConfigMoney()); // my custom params only for that object
许多类型已准备好使用
SimpleTypes有如下已配置的示例
你可以添加自己的类型。这非常简单。请参阅下面的页面。
智能且实用的解析器
SimpleTypes为所有输入值拥有一个真正智能的解析器。它可以找到数字、理解任何十进制符号、去除空格、字母大小写等...并且它运行得非常快!
$money = new Money(' - 1 2 3 , 4 5 6 rub '); // Equals -123.456 rubles $money = new Money('1.0e+18 EUR '); // Really huge number. I'm rich! =) $money = new Money(' EuR 3,50 '); $money = new Money('usd'); // Just object with usd rule
方法链调用
$value = (new Money('4.95 usd')) ->add('10 usd') // $14.95 ->subtract('2 eur') // $10.95 ->negative() // -$10.95 ->getClone() // copy of object is created ->division(5) // -$2.19 ->multiply(10) // -$21.90 ->convert('eur') // -10.95€ (For easy understanding we use 1 EUR = 2 USD) ->customFunc(function (Money $value) { // sometimes we would like something more than plus/minus ;) $value ->add(new Money('600 rub')) // 1.05€ (1 EUR = 50 RUB) ->add('-500%'); // -4.2€ }) ->abs(); // 4.2€
基本算术
使用基本算术的不同方式
// example #1 $usd = new Money('10 usd'); $usd->add(new Money('10 eur')); // example #2 $usd = (new Money('10 usd'))->add(new Money('10 eur')); // example #3 $usd->add('10 eur'); // example #4 $usd->add('10'); // eur is default in the ConfigMoney // example #5 $usd->add(['10', 'eur']);
SimpleTypes可以
- 添加
- 减去
- 除法
- 乘法
- 使用自定义函数(闭包)
- 负数 / 正数 / 取反 / 绝对值
- 使用百分比
- 设置空值
- 设置另一个值和规则
- 创建克隆
- 转换为任何规则(货币、单位)
- 四舍五入
- 比较
- ...以及其他
比较值
$kg = new Weight('1 kg'); // one kilogram $lb = new Weight('2 lb'); // two pounds var_dump($kg->compare($lb)); // false ("==" by default) var_dump($kg->compare($lb, '==')); // false var_dump($kg->compare($lb, '<')); // false var_dump($kg->compare($lb, '<=')); // false var_dump($kg->compare($lb, '>')); // true var_dump($kg->compare($lb, '>=')); // true
同样的例子,但我们将使用智能解析器
$kg = new Weight('1 kg'); $lb = new Weight('2 lb'); var_dump($kg->compare('1000 g')); // true var_dump($kg->compare('2 lb', '==')); // false var_dump($kg->compare('2 lb', '<')); // false var_dump($kg->compare('2 lb', '<=')); // false var_dump($kg->compare('2 lb', '>')); // true var_dump($kg->compare('2 lb', '>=')); // true
百分比方法
计算两个值之间差异的简单方法
$origPrice = new Money('100 usd'); $realPrice = new Money('40 eur'); $diff = $realPrice->percent($origPrice); echo $diff->text(); // 80% $discount = $realPrice->percent($origPrice, true); // revert flag added echo $discount->text(); // 20%
PHP魔术方法
安全的序列化/反序列化
$valBefore = $this->val('500 usd'); $valString = serialize($valBefore); $valAfter = unserialize($valString)->convert('eur'); $valBefore->compare($valAfter);// true
__toString()就像text()方法一样工作
$val = $this->val('500 usd'); echo $val; // "$500.00"
__invoke()
$val = $this->val('10 eur'); // it's converting $val('usd'); // so object now contains "20 usd" (1 eur = 2 usd) // set new value and rule $val('100 rub'); $val('100', 'uah');
不同的输出和渲染方式
仅文本
$value = new Money('-50.666666 usd'); echo $value->text(); // "-$50.67" echo $value->text('rub'); // "-1 266,67 руб." (output without changing inner state) echo $value->noStyle('rub'); // "-1 266,67" (without symbol)
简单的HTML渲染
echo (new Money('-50.666666 usd'))->html('rub'); // render HTML, useful for JavaScript
输出(添加包装仅为了清晰)
<span class="simpleType simpleType-block simpleType-money" data-simpleType-id="1" data-simpleType-value="-1266.66665" data-simpleType-rule="rub" data-simpleType-orig-value="-50.666666" data-simpleType-orig-rule="usd"> -<span class="simpleType-value">1 266,67</span> <span class="simpleType-symbol">руб.</span> </span>
HTML输入类型[text]
echo $value->htmlInput('rub', 'input-name-attr');
输出(添加包装仅为了清晰)
<input value="-1 266,67" name="input-name-attr" type="text" class="simpleType simpleType-money simpleType-input" data-simpleType-id="1" data-simpleType-value="-1266.66665" data-simpleType-rule="rub" data-simpleType-orig-value="-50.666666" data-simpleType-orig-rule="usd" />
注意:是的,我们在HTML代码中添加了许多data-attributes。这将为JavaScript和页面不重新加载的转换提供便利。
类型的配置
所有配置类都应扩展自Config类。例如,信息的配置
/** * Class ConfigInfo * @package JBZoo\SimpleTypes */ class ConfigInfo extends Config { /** * SimpleTypes uses it for converting and while parsing undefined values * @var string */ public $default = 'byte'; /** * To collect or not to collect logs for each object (need additional memory a little bit) * @var bool */ public $isDebug = true; /** * Array of converting rules and output format * return array */ public function getRules() { // key of array is alias for parser return array( 'byte' => array( 'rate' => 1 // Because 1 byte to byte is 1 =))) ), 'kb' => array( 'symbol' => 'KB', // symbol for output (->text(), ->html(), ...) 'round_type' => Formatter::ROUND_CLASSIC, // classic, float, ceil, none 'round_value' => Formatter::ROUND_DEFAULT, // Count of valuable number after decimal point for any arithmetic actions 'num_decimals' => '2', // Sets the number of decimal points 'decimal_sep' => '.', // Sets the separator for the decimal point. 'thousands_sep' => ' ', // Sets the thousands separator. 'format_positive' => '%v %s', // %v - replace to rounded and formated (number_format()) value 'format_negative' => '-%v %s', // %s - replace to symbol 'rate' => 1024, // How many bytes (default measure) in the 1 KB ? ), 'mb' => array( // Other params gets from $this->defaultParams variable 'symbol' => 'MB', 'rate' => 1024 * 1024, ), 'gb' => array( // Other params gets from $this->defaultParams variable 'symbol' => 'GB', 'rate' => 1024 * 1024 * 1024, ), 'bit' => array( 'symbol' => 'Bit', 'rate' => function ($value, $to) { // Custom callback function for difficult conversion if ($to == 'bit') { return $value * 8; } return $value / 8; }, ), ); } }
我们的信息类型的用法示例
// create config object $config = new ConfigInfo(); // you can register default config for all info-objects, Config::registerDefault('info', $config); $info1 = new Info('700 MB'); $info2 = new Info('1.4 GB'); // or add config object manually $info1 = new Info('700 MB', $config); $info2 = new Info('1.4 GB', $config); // Well... some calculations echo $info2->subtract($info1)->dump() . PHP_EOL; echo $info2->convert('mb')->dump() . PHP_EOL; print_r($info2->logs());
输出
0.71640625 gb; id=4
733.6 mb; id=4
Array
(
[0] => Id=4 has just created; dump="1.4 gb"
[1] => Subtract "700 mb"; New value = "0.71640625 gb"
[2] => Converted "gb"=>"mb"; New value = "733.6 mb"; 1 gb = 1024 mb
)
调试信息
显示对象的所有动作列表。例如,这是链式代码的历史记录
print_r($value->logs()); /** * Array * ( * [0] => Id=16 has just created; dump="4.95 usd" * [1] => Add "10 usd"; New value = "14.95 usd" * [2] => Subtract "2 eur"; New value = "10.95 usd" * [3] => Set negative; New value = "-10.95 usd" * [4] => Cloned from id=16 and created new with id=19; dump=-10.95 usd * [5] => Division with "5"; New value = "-2.19 usd" * [6] => Multiply with "10"; New value = "-21.9 usd" * [7] => Converted "usd"=>"eur"; New value = "-10.95 eur"; 1 usd = 0.5 eur * [8] => --> Function start * [9] => Add "600 rub"; New value = "1.05 eur" * [10] => Add "-500 %"; New value = "-4.2 eur" * [11] => <-- Function finished; New value = "-4.2 eur" * [12] => Set positive/abs; New value = "4.2 eur" * ) */
显示不带任何格式化和四舍五入的真实内部数据。ID是SimpleType对象的唯一数字。
echo $value->dump(); // "4.2 eur; id=19"
获取对象ID
echo $value->getId(); // "19"
显示当前值
echo $value->val(); // "4.2"
显示当前规则
echo $value->rule(); // "eur"
许可证
MIT