forked from contributte/datagrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColumnNumber.php
76 lines (59 loc) · 1.31 KB
/
ColumnNumber.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php declare(strict_types = 1);
namespace Contributte\Datagrid\Column;
use Contributte\Datagrid\Row;
class ColumnNumber extends Column
{
protected ?string $align = 'end';
protected array $numberFormat = [
0, // Decimals
'.', // Decimal point
' ', // Thousands separator
];
public function getColumnValue(Row $row): mixed
{
$value = parent::getColumnValue($row);
if (!is_numeric($value)) {
return $value;
}
$decimal = null;
$value = (string) $value;
if (str_contains($value, '.')) {
list($integer, $decimal) = explode('.', $value, 2);
}
else {
$integer = $value;
}
if ($this->numberFormat[0] > 0) {
$decimal = substr(
$decimal . str_repeat('0', $this->numberFormat[0]),
0,
$this->numberFormat[0]
);
}
$integer = preg_replace('/\B(?=(\d{3})+(?!\d))/', $this->numberFormat[2], $integer);
if ($decimal > 0) {
return $integer . $this->numberFormat[1] . $decimal;
}
return $integer;
}
/**
* @return static
*/
public function setFormat(
int $decimals = 0,
string $decPoint = '.',
string $thousandsSep = ' '
): self
{
$this->numberFormat = [$decimals, $decPoint, $thousandsSep];
return $this;
}
public function getFormat(): array
{
return [
$this->numberFormat[0],
$this->numberFormat[1],
$this->numberFormat[2],
];
}
}