unit/信息

用于计算和格式化信息单元的包,如比特、字节、千比特、千字节、兆比特、兆字节等。

v1.2.0 2021-07-10 04:26 UTC

This package is auto-updated.

Last update: 2024-09-10 11:06:24 UTC


README

用于计算和格式化信息单元的包,如比特、字节、千比特、千字节、兆比特、兆字节等。

Total Downloads Version

安装

user@machine:~$ composer require unit/information

单元

使用的单元遵循 IEC 标准。

使用方法

智能格式化

use Unit\Information\Size;

// Format 1 Byte
(new Size(1))->format(); // "1B"

// Format Byte values
(new Size(4300000))->format();     // "4.3MB"
(new Size(73042346800))->format(); // "73.0423468GB"

// Cut at precision
(new Size(73042346800))->format(null);    // "73GB"
(new Size(73042346800))->format(null, 0); // "73GB"
(new Size(73042346800))->format(null, 2); // "73.04GB"

// Custom format
(new Size(73042346800))->format(null, 1, '%size% %unit_abbreviation% (%unit_name%)'); // "73.0 GB (Gigabyte)"

以指定单位格式化值

use Unit\Information\Size;
use Unit\Information\Unit;

(new Size(73042346800))->format(Unit::MEGABYTE); // "73042MB"
(new Size(300000))->format(Unit::MEGABYTE, 1);   // "0.3MB"

将值转换为另一个单位(非格式化字符串)的数字值

use Unit\Information\Size;
use Unit\Information\Unit;

(new Size(100000))->get(Unit::KILOBYTE); // 100
(new Size(1))->get(Unit::KILOBYTE);      // 0.001

从指定单位的值创建大小

use Unit\Information\Size;

new Size(1);     // If the value is not a string it is treated as a Byte value which is transformed to a Bit value internally
new Size('1MB'); // If it is a string the string is transformed to a Bit value intelligently
new Size('0.05GB');

计算

use Unit\Information\Size;

$size = new Size(1);
$otherSize = new Size('1MB');

$size->add($otherSize);
$size->subtract($otherSize);
$size->multiply($otherSize);
$size->divide($otherSize);

$size->add($otherSize)->subtract($otherSize); // Can be chained

从 PHP 的简写值(不遵循 IEC 标准,见 https://php.ac.cn/manual/en/faq.using.php#faq.using.shorthandbytes)实例化

use Unit\Information\Size;
use Unit\Information\InvalidPhpShorthandValueException;

$size = Size::createFromPhpShorthandValue('1M'); // Results in 1048576 Bytes
try {
    $size = Size::createFromPhpShorthandValue(ini_get('memory_limit'));
} catch (InvalidPhpShorthandValueException $exception) {
    // $exception->getMessage() is: 'The PHP shorthand value "-1" cannot be converted to a meaningful size.'
}

开发

对于某些开发工具,需要安装 Symfony 二进制文件

user@machine:~$ wget https://get.symfony.com/cli/installer -O - | bash

为开发建立仓库

user@machine:~$ git clone git@github.com:michaelKaefer/money-bundle.git
user@machine:~$ cd money-bundle/
user@machine:~$ make build-dev

测试

user@machine:~$ make tests
// Build PHP code coverage
user@machine:~$ make code-coverage

代码风格检查

user@machine:~$ make composer-validate
user@machine:~$ make security-check
user@machine:~$ make psalm-dry-run
user@machine:~$ make cs-fixer-dry-run

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件