Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
SizeConverter
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
2 / 2
4
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 convertHumanReadableByte
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3declare(strict_types=1);
4
5namespace PeServer\Core;
6
7use PeServer\Core\Collection\Arr;
8
9/**
10 * データ容量変換。
11 */
12readonly class SizeConverter
13{
14    #region define
15
16    /**
17     * 1KB のサイズ。
18     */
19    public const KB_SIZE = 1024;
20
21    /**
22     * サイズ単位。
23     *
24     * @var string[]
25     */
26    public const UNITS = [
27        'byte', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB',
28    ];
29
30    #endregion
31
32    /**
33     * 生成。
34     *
35     * @param int $kbSize 1KB のサイズ。
36     * @param string[] $units サイズ単位。
37     */
38    public function __construct(
39        private int $kbSize = self::KB_SIZE,
40        private array $units = self::UNITS
41    ) {
42    }
43
44    #region function
45
46    /**
47     * 読みやすいように変換。
48     *
49     * C#(Pe.Core)から移植。
50     *
51     * @param int $byteSize
52     * @param string $sizeFormat {f_size} {i_size} {unit}
53     * @phpstan-param literal-string $sizeFormat
54     * @return string
55     */
56    public function convertHumanReadableByte(int $byteSize, string $sizeFormat = '{i_size} {unit}'): string
57    {
58        $size = $byteSize;
59        $order = 0;
60        $unitCount = Arr::getCount($this->units);
61        while ($size >= $this->kbSize && ++$order < $unitCount) {
62            $size = $size / $this->kbSize;
63        }
64
65        return Text::replaceMap($sizeFormat, [
66            'f_size' => strval(round($size, 2)),
67            'i_size' => strval($size),
68            'unit' => $this->units[$order]
69        ]);
70    }
71
72    #endregion
73}