Test Failed
Push — renovate/major-composer-qa-too... ( 6faed2...5f6191 )
by
unknown
11:41
created

PostgresJsonToPHPArrayTransformer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 20
c 1
b 1
f 0
dl 0
loc 46
ccs 0
cts 19
cp 0
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A transformPostgresJsonEncodedValueToPHPValue() 0 7 2
A transformPostgresArrayToPHPArray() 0 13 3
A transformPostgresJsonEncodedValueToPHPArray() 0 11 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MartinGeorgiev\Utils;
6
7
use MartinGeorgiev\Doctrine\DBAL\Types\Exceptions\InvalidJsonArrayItemForPHPException;
8
use MartinGeorgiev\Doctrine\DBAL\Types\Exceptions\InvalidJsonItemForPHPException;
9
10
/**
11
 * Handles transformation from PostgreSQL JSON(B) values to PHP values.
12
 *
13
 * @since 3.0
14
 *
15
 * @author Martin Georgiev <[email protected]>
16
 */
17
class PostgresJsonToPHPArrayTransformer
18
{
19
    private const POSTGRESQL_EMPTY_ARRAY = '{}';
20
21
    public static function transformPostgresArrayToPHPArray(string $postgresValue): array
22
    {
23
        if ($postgresValue === self::POSTGRESQL_EMPTY_ARRAY) {
24
            return [];
25
        }
26
27
        $trimmedPostgresArray = \mb_substr($postgresValue, 2, -2);
28
        $phpArray = \explode('},{', $trimmedPostgresArray);
29
        foreach ($phpArray as &$item) {
30
            $item = '{'.$item.'}';
31
        }
32
33
        return $phpArray;
34
    }
35
36
    /**
37
     * @throws InvalidJsonArrayItemForPHPException When the PostgreSQL value is not a JSON
38
     */
39
    public static function transformPostgresJsonEncodedValueToPHPArray(string $postgresValue): array
40
    {
41
        try {
42
            $transformedValue = \json_decode($postgresValue, true, 512, JSON_THROW_ON_ERROR);
43
            if (!\is_array($transformedValue)) {
44
                throw InvalidJsonArrayItemForPHPException::forInvalidType($postgresValue);
45
            }
46
47
            return $transformedValue;
48
        } catch (\JsonException) {
49
            throw InvalidJsonArrayItemForPHPException::forInvalidFormat($postgresValue);
50
        }
51
    }
52
53
    /**
54
     * @throws InvalidJsonItemForPHPException When the PostgreSQL value is not JSON-decodable
55
     */
56
    public static function transformPostgresJsonEncodedValueToPHPValue(string $postgresValue): null|array|bool|float|int|string
57
    {
58
        try {
59
            // @phpstan-ignore-next-line
60
            return \json_decode($postgresValue, true, 512, JSON_THROW_ON_ERROR);
61
        } catch (\JsonException) {
62
            throw InvalidJsonItemForPHPException::forInvalidType($postgresValue);
63
        }
64
    }
65
}
66