Value   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 14
dl 0
loc 29
rs 10
c 1
b 1
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A transformNumber() 0 5 3
A transform() 0 7 1
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