JsonObject::get()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 2
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace Composed;
3
4
/**
5
 * @author Josh Di Fabio <[email protected]>
6
 */
7
class JsonObject
8
{
9
    private $data;
10
11
    public function __construct(array $data)
12
    {
13
        $this->data = $data;
14
    }
15
16
    public static function fromFilePath(string $filePath) : self
17
    {
18
        if (false === $fileContent = @file_get_contents($filePath)) {
19
            if (!file_exists($filePath)) {
20
                throw new \RuntimeException("File not found: $filePath");
21
            }
22
23
            throw new \RuntimeException("Failed to open file: $filePath");
24
        }
25
26
        if (null === $data = json_decode($fileContent, true)) {
27
            throw new \RuntimeException("File does not contain valid JSON: $filePath");
28
        }
29
30
        return self::fromArray($data);
31
    }
32
33
    public static function fromArray(array $data) : self
34
    {
35
        return new self($data);
36
    }
37
38
    public function get($keys = [], $default = null)
39
    {
40
        if (!is_array($keys)) {
41
            $keys = [$keys];
42
        }
43
        
44
        if (!$keys) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $keys of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
45
            return $this->data;
46
        }
47
48
        return $this->deepGet($this->data, $keys, $default);
49
    }
50
51
    private function deepGet(array $current, array $keys = [], $default = null)
52
    {
53
        foreach ($keys as $key) {
54
            if (!is_array($current) || !array_key_exists($key, $current)) {
55
                return $default;
56
            }
57
            $current = $current[$key];
58
        }
59
60
        return $current;
61
    }
62
}
63