JsonObject::setOptionalProperty()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Aweapi\Openapi;
6
7
use JsonSerializable;
8
use stdClass;
9
10
final class JsonObject implements JsonSerializable
11
{
12
    private $data = [];
13
14 1
    public function jsonSerialize()
15
    {
16 1
        return $this->data ?: self::emptyObject();
17
    }
18
19
    /**
20
     * @param mixed $value
21
     */
22 1
    public function setOptionalProperty(string $name, $value): void
23
    {
24 1
        if (!self::isEmpty($value)) {
25 1
            $this->setRequiredProperty($name, $value);
26
        }
27
    }
28
29
    /**
30
     * @param mixed $value
31
     */
32 1
    public function setRequiredNestedProperty(string $name, $value): void
33
    {
34 1
        $this->setRequiredProperty(
35 1
            $name,
36 1
            self::isEmpty($value)
37 1
                ? self::emptyObject()
38 1
                : $value
39
        );
40
    }
41
42
    /**
43
     * @param mixed $value
44
     */
45 1
    public function setRequiredProperty(string $name, $value): void
46
    {
47 1
        $this->data[$name] = $value;
48
    }
49
50
    /**
51
     * Use this instead of empty maps for required properties to force JSON-object.
52
     */
53 1
    private static function emptyObject(): stdClass
54
    {
55 1
        return new stdClass();
56
    }
57
58
    /**
59
     * @param mixed $value
60
     */
61 1
    private static function isEmpty($value): bool
62
    {
63 1
        if ($value instanceof JsonSerializable) {
0 ignored issues
show
Bug introduced by
The class JsonSerializable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
64 1
            return self::isEmpty($value->jsonSerialize());
65
        }
66
67 1
        return empty($value);
68
    }
69
}
70