FormatNumber::getCallablesTable()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EngineWorks\Templates\Plugins;
6
7
use EngineWorks\Templates\Plugin;
8
use InvalidArgumentException;
9
10
class FormatNumber implements Plugin
11
{
12
    /**
13
     * @return array{fn: string}
14
     */
15 1
    public function getCallablesTable(): array
16
    {
17
        return [
18 1
            'fn' => 'format',
19
        ];
20
    }
21
22
    /** @var int */
23
    private $defaultDecimals;
24
25 6
    public function __construct(int $defaultDecimals = 2)
26
    {
27 6
        $this->setDefaultDecimals($defaultDecimals);
28
    }
29
30
    /**
31
     * Format a number, if the expression is not a number, then uses 0
32
     *
33
     * @param mixed $number
34
     * @param int $decimals = $this->defaultDecimals()
35
     */
36 1
    public function format($number, int $decimals = -1): string
37
    {
38 1
        if ($decimals < 0) {
39 1
            $decimals = $this->getDefaultDecimals();
40
        }
41 1
        return number_format(is_numeric($number) ? (float) $number : 0, $decimals);
42
    }
43
44 4
    public function getDefaultDecimals(): int
45
    {
46 4
        return $this->defaultDecimals;
47
    }
48
49 6
    public function setDefaultDecimals(int $defaultDecimals): void
50
    {
51 6
        if ($defaultDecimals < 0) {
52 1
            throw new InvalidArgumentException('The default decimals argument is not an integer greater than zero');
53
        }
54 6
        $this->defaultDecimals = $defaultDecimals;
55
    }
56
}
57