JsonUtils   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 33
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A toArray() 0 9 2
A toString() 0 8 2
1
<?php
2
3
/**
4
 * Static Analysis Results Baseliner (sarb).
5
 *
6
 * (c) Dave Liddament
7
 *
8
 * For the full copyright and licence information please view the LICENSE file distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace DaveLiddament\StaticAnalysisResultsBaseliner\Domain\Utils;
14
15
use DaveLiddament\StaticAnalysisResultsBaseliner\Domain\File\InvalidContentTypeException;
16
17
final class JsonUtils
18
{
19
    /**
20
     * Returns JSON string as an associative array representation.
21
     *
22
     * @throws InvalidContentTypeException
23
     *
24
     * @return array<mixed>
25
     */
26
    public static function toArray(string $jsonAsString): array
27
    {
28
        /** @psalm-suppress MixedAssignment */
29
        $asArray = json_decode($jsonAsString, true);
30
        if (!is_array($asArray)) {
31
            throw InvalidContentTypeException::notJson();
32
        }
33
34
        return $asArray;
35
    }
36
37
    /**
38
     * Converts array to a JSON representation in a string.
39
     *
40
     * @param array<mixed> $data
41
     */
42
    public static function toString(array $data): string
43
    {
44
        $asString = json_encode($data, \JSON_UNESCAPED_UNICODE | \JSON_PRETTY_PRINT);
45
        if (false === $asString) {
46
            throw new \LogicException('Can not convert data to JSON string');
47
        }
48
49
        return $asString;
50
    }
51
}
52