Completed
Push — master ( 8b1d39...e6cddd )
by Jakob
01:31
created

PrettyJsonSerializable::jsonLDSerialize()   C

Complexity

Conditions 14
Paths 45

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
c 0
b 0
f 0
rs 5.0864
cc 14
eloc 25
nc 45
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php declare(strict_types = 1);
2
3
namespace JSKOS;
4
5
/**
6
 * Provide consistent JSON(-LD) serializing.
7
 */
8
abstract class PrettyJsonSerializable implements \JsonSerializable
9
{
10
    const DEFAULT_CONTEXT = 'https://gbv.github.io/jskos/context.json';
11
12
    /**
13
     * Returns data which should be serialized to JSON.
14
     *
15
     * Delegates to jsonLDSerialize which can be called with a JSON-LD context URL.
16
     */
17
    public function jsonSerialize()
18
    {
19
        return $this->jsonLDSerialize();
20
    }
21
22
    /**
23
     * Returns data which should be serialized to JSON.
24
     *
25
     * Include all non-null members and the JSON-LD context (`@context`).
26
     * Keys are sorted by Unicode codepoint for stable output.
27
     *
28
     * @param string $context optional JSON-LD context URL. Use empty string to omit.
29
     */
30
    public function jsonLDSerialize(string $context = self::DEFAULT_CONTEXT)
31
    {
32
        $json = [];
33
34
        foreach ($this as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $this of type this<JSKOS\PrettyJsonSerializable> is not traversable.
Loading history...
35
            if (isset($value)) {
36
                if ($value instanceof PrettyJsonSerializable) {
37
                    $value = $value->jsonLDSerialize('');
38
                } elseif (is_array($value) and !count(array_filter(array_keys($value), 'is_string'))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
39
                    $a = [];
40
                    foreach ($value as $m) {
41
                        if ($m instanceof PrettyJsonSerializable) {
42
                            $m = $m->jsonLDSerialize('');
43
                        }
44
                        $a[] = $m;
45
                    }
46
                    $value = $a;
47
                }
48
                $json[$key] = $value;
49
            }
50
        }
51
52
        if ($context) {
53
            $json['@context'] = $context;
54
            $types = defined(get_called_class() . '::TYPES') ? static::TYPES : [];
55
            if (property_exists($this, 'type') and count($types)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
56
                if (isset($json['type'])) {
57
                    if (empty(array_intersect($json['type'], $types))) {
58
                        array_unshift($json['type'], $types[0]);
59
                    }
60
                } else {
61
                    $json['type'] = [$types[0]];
62
                }
63
            }
64
        }
65
66
        ksort($json);
67
        return $json;
68
    }
69
70
    /**
71
     * Serialize to JSON in string context.
72
     */
73
    public function __toString()
74
    {
75
        return json_encode($this, JSON_UNESCAPED_SLASHES);
76
    }
77
78
    /**
79
     * Serialize to pretty-printed JSON.
80
     */
81
    public function json()
82
    {
83
        return json_encode($this, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
84
    }
85
}
86