JsonStringFormatter   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 52
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isJsonHeader() 0 4 1
A isJsonString() 0 15 4
A format() 0 10 2
1
<?php
2
3
namespace Glooby\Debug\Formatter;
4
5
/**
6
 * @author Emil Kilhage
7
 */
8
class JsonStringFormatter implements FormatterInterface
9
{
10
    /**
11
     * @var array
12
     */
13
    private static $headers = [
14
        'application/json',
15
    ];
16
17
    /**
18
     * @param string $header
19
     * @return bool
20
     */
21
    public static function isJsonHeader($header)
22
    {
23
        return in_array($header, self::$headers, true);
24
    }
25
26
    /**
27
     * @param string $string
28
     * @return bool
29
     */
30
    public static function isJsonString($string)
31
    {
32
        $string = trim($string);
33
34
        if (substr($string, 0, 1) === '{' && substr($string, -1, 1) === '}') {
35
            try {
36
                json_decode($string);
37
                return json_last_error() === JSON_ERROR_NONE;
38
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
39
40
            }
41
        }
42
43
        return false;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function format($response)
50
    {
51
        try {
52
            $response = \GuzzleHttp\Utils::jsonDecode($response);
53
54
            return json_encode($response, JSON_PRETTY_PRINT);
55
        } catch (\Exception $e) {
56
            return $response;
57
        }
58
    }
59
}
60