Passed
Pull Request — master (#4115)
by Owen
15:19
created

Trunc::evaluate()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 8

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 34
ccs 12
cts 12
cp 1
rs 8.4444
c 0
b 0
f 0
cc 8
nc 10
nop 2
crap 8
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Calculation\MathTrig;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled;
6
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
7
8
class Trunc
9
{
10
    use ArrayEnabled;
11
12
    /**
13
     * TRUNC.
14
     *
15
     * Truncates value to the number of fractional digits by number_digits.
16
     *
17
     * @param array|float $value Or can be an array of values
18
     * @param array|int $digits Or can be an array of values
19
     *
20
     * @return array|float|string Truncated value, or a string containing an error
21
     *         If an array of numbers is passed as an argument, then the returned result will also be an array
22
     *            with the same dimensions
23
     */
24 30
    public static function evaluate(array|float|string|null $value = 0, array|int|string $digits = 0): array|float|string
25
    {
26 30
        if (is_array($value) || is_array($digits)) {
27 5
            return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $digits);
28
        }
29
30
        try {
31 30
            $value = Helpers::validateNumericNullBool($value);
32 28
            $digits = Helpers::validateNumericNullSubstitution($digits, null);
33 3
        } catch (Exception $e) {
34 3
            return $e->getMessage();
35
        }
36
37 27
        if ($value == 0) {
38
            return $value;
39
        }
40 27
41
        if ($value >= 0) {
42 27
            $minusSign = '';
43 2
        } else {
44
            $minusSign = '-';
45
            $value = -$value;
46 25
        }
47
        $digits = (int) floor($digits);
48
        if ($digits < 0) {
49
            $power = (int) (10 ** -$digits);
50
            $result = intdiv((int) floor($value), $power) * $power;
51
52
            return ($minusSign === '') ? $result : -$result;
53
        }
54
        $digitsPlus1 = $digits + 1;
55
        $result = substr($minusSign . sprintf("%.{$digitsPlus1}f", $value), 0, -1);
56
57
        return (float) $result;
58
    }
59
}
60