ValueParser::parse()   B
last analyzed

Complexity

Conditions 9
Paths 8

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 9.648

Importance

Changes 0
Metric Value
cc 9
eloc 17
c 0
b 0
f 0
nc 8
nop 2
dl 0
loc 23
ccs 4
cts 5
cp 0.8
crap 9.648
rs 8.0555
1
<?php
2
/**
3
 * This file is part of the eav package.
4
 * @author    Alex Kuperwood <[email protected]>
5
 * @copyright 2025 Alex Kuperwood
6
 * @license   https://opensource.org/license/mit  The MIT License
7
 */
8
9
namespace Kuperwood\Eav\Value;
10
11
use DateTime;
12
use Kuperwood\Eav\Enum\ATTR_TYPE;
13
use InvalidArgumentException;
14
15
class ValueParser
16
{
17
    /**
18
     * @throws \Exception
19
     */
20 1
    public function parse($type, $value)
21
    {
22
        switch ($type) {
23
            case ATTR_TYPE::INTEGER:
24
                return (int) $value;
25
            case ATTR_TYPE::STRING:
26
            case ATTR_TYPE::TEXT:
27 1
            case ATTR_TYPE::MANUAL:
28
                return $value;
29 1
            case ATTR_TYPE::DATETIME:
30
                return (new DateTime($value))->format('Y-m-d H:i:s');
31 1
            case ATTR_TYPE::DECIMAL:
32
                $valueStr = (string)$value;
33
                // Find the position of the decimal point
34
                $decimalPos = strpos($valueStr, '.');
35
                // If there is a decimal point and more than 6 decimals
36
                if ($decimalPos !== false && strlen($valueStr) > $decimalPos + 7) {
37
                    // Cut the value after 6 decimals
38
                    $valueStr = substr($valueStr, 0, $decimalPos + 7);
39
                }
40
                return rtrim(rtrim($valueStr, '0'), '.');
41
            default:
42
                throw new InvalidArgumentException("Unknown attribute type: " . $type);
43
        }
44
    }
45
}