Passed
Push — main ( 339e98...90c0a6 )
by Martin
40:38 queued 25:40
created

PostgresJsonToPHPArrayTransformer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 20
c 1
b 1
f 0
dl 0
loc 46
ccs 19
cts 19
cp 1
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 7
    public static function transformPostgresArrayToPHPArray(string $postgresValue): array
22
    {
23 7
        if ($postgresValue === self::POSTGRESQL_EMPTY_ARRAY) {
24 2
            return [];
25
        }
26
27 5
        $trimmedPostgresArray = \mb_substr($postgresValue, 2, -2);
28 5
        $phpArray = \explode('},{', $trimmedPostgresArray);
29 5
        foreach ($phpArray as &$item) {
30 5
            $item = '{'.$item.'}';
31
        }
32
33 5
        return $phpArray;
34
    }
35
36
    /**
37
     * @throws InvalidJsonArrayItemForPHPException When the PostgreSQL value is not a JSON
38
     */
39 7
    public static function transformPostgresJsonEncodedValueToPHPArray(string $postgresValue): array
40
    {
41
        try {
42 7
            $transformedValue = \json_decode($postgresValue, true, 512, JSON_THROW_ON_ERROR);
43 4
            if (!\is_array($transformedValue)) {
44 1
                throw InvalidJsonArrayItemForPHPException::forInvalidType($postgresValue);
45
            }
46
47 3
            return $transformedValue;
48 4
        } catch (\JsonException) {
49 3
            throw InvalidJsonArrayItemForPHPException::forInvalidFormat($postgresValue);
50
        }
51
    }
52
53
    /**
54
     * @throws InvalidJsonItemForPHPException When the PostgreSQL value is not JSON-decodable
55
     */
56 15
    public static function transformPostgresJsonEncodedValueToPHPValue(string $postgresValue): null|array|bool|float|int|string
57
    {
58
        try {
59
            // @phpstan-ignore-next-line
60 15
            return \json_decode($postgresValue, true, 512, JSON_THROW_ON_ERROR);
61 1
        } catch (\JsonException) {
62 1
            throw InvalidJsonItemForPHPException::forInvalidType($postgresValue);
63
        }
64
    }
65
}
66