Skip to content

Commit b2928ae

Browse files
authored
[Feature] Extend number helper (alexjustesen#1082)
1 parent 0eb603f commit b2928ae

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

app/Helpers/Number.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace App\Helpers;
4+
5+
use Illuminate\Support\Number as SupportNumber;
6+
7+
class Number extends SupportNumber
8+
{
9+
/**
10+
* Convert the given number to its file size equivalent in bits.
11+
*/
12+
public static function fileSizeBits(int|float $bits, int $precision = 0, ?int $maxPrecision = null, bool $perSecond = false): string
13+
{
14+
$units = match ($perSecond) {
15+
true => ['Bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps'],
16+
default => ['B', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb']
17+
};
18+
19+
for ($i = 0; ($bits / 1024) > 0.9 && ($i < count($units) - 1); $i++) {
20+
$bits /= 1024;
21+
}
22+
23+
return sprintf('%s %s', static::format($bits, $precision, $maxPrecision), $units[$i]);
24+
}
25+
}

app/Models/Result.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Models;
44

55
use App\Events\ResultCreated;
6+
use Illuminate\Database\Eloquent\Casts\Attribute;
67
use Illuminate\Database\Eloquent\Factories\HasFactory;
78
use Illuminate\Database\Eloquent\Model;
89
use Illuminate\Support\Arr;
@@ -106,4 +107,28 @@ public function getJitterData(): array
106107
'ping' => $data['ping']['jitter'] ?? null,
107108
];
108109
}
110+
111+
/**
112+
* Get the result's download in bits.
113+
*/
114+
protected function downloadBits(): Attribute
115+
{
116+
return Attribute::make(
117+
get: fn (mixed $value): ?string => ! blank($this->download) && is_numeric($this->download)
118+
? number_format(num: $this->download * 8, decimals: 0, thousands_separator: '')
119+
: null,
120+
);
121+
}
122+
123+
/**
124+
* Get the result's upload in bits.
125+
*/
126+
protected function uploadBits(): Attribute
127+
{
128+
return Attribute::make(
129+
get: fn (mixed $value): ?string => ! blank($this->upload) && is_numeric($this->upload)
130+
? number_format(num: $this->upload * 8, decimals: 0, thousands_separator: '')
131+
: null,
132+
);
133+
}
109134
}

0 commit comments

Comments
 (0)