Value::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types = 1);
2
3
namespace Spaghetti\XLSXParser\Transformer;
4
5
use DateTimeImmutable;
6
use Spaghetti\XLSXParser\SharedStrings;
7
use Spaghetti\XLSXParser\Styles;
8
9
use function filter_var;
10
use function trim;
11
12
use const FILTER_VALIDATE_BOOL;
13
14
/**
15
 * @internal
16
 */
17
final class Value
18
{
19
    private const BOOL = 'b';
20
    private const EMPTY = '';
21
    private const NUMBER = 'n';
22
    private const SHARED_STRING = 's';
23
24
    private readonly Date $dateTransformer;
25
26
    public function __construct(private readonly SharedStrings $sharedStrings, private readonly Styles $styles, ?Date $dateTransformer = null)
27
    {
28
        $this->dateTransformer = $dateTransformer ?? new Date();
0 ignored issues
show
Bug introduced by
The property dateTransformer is declared read-only in Spaghetti\XLSXParser\Transformer\Value.
Loading history...
29
    }
30
31
    public function transform(string $value, string $type, string $style): bool|DateTimeImmutable|float|int|string
32
    {
33
        return match ($type) {
34
            self::BOOL => filter_var(value: $value, filter: FILTER_VALIDATE_BOOL),
35
            self::SHARED_STRING => trim(string: $this->sharedStrings->get(index: (int) $value)),
36
            self::EMPTY, self::NUMBER => $this->transformNumber(style: $style, value: $value),
37
            default => trim(string: $value),
38
        };
39
    }
40
41
    private function transformNumber(string $style, mixed $value): DateTimeImmutable|float|int
42
    {
43
        return match (true) {
44
            $style && Styles::FORMAT_DATE === $this->styles->get(index: (int) $style) => $this->dateTransformer->transform(value: (int) $value),
45
            default => preg_match(pattern: '/^\d+\.\d+$/', subject: $value) ? (float) $value : (int) $value,
46
        };
47
    }
48
}
49