Completed
Push — master ( ff6b34...f0b204 )
by Garrett
06:01
created

Json::load()   D

Complexity

Conditions 9
Paths 24

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
c 5
b 0
f 1
dl 0
loc 37
rs 4.909
cc 9
eloc 22
nc 24
nop 2
1
<?php
2
3
/* @description Dice - A minimal Dependency Injection Container for PHP
4
 * @author      Tom Butler [email protected]
5
 * @copyright   2012-2014 Tom Butler <[email protected]>
6
 * @link        http://r.je/dice.html
7
 * @license     http://www.opensource.org/licenses/bsd-license.php  BSD License
8
 * @version     2.0
9
 */
10
11
namespace Dice\Loader;
12
13
class Json
14
{
15
    public function load($json, \Dice\Dice $dice = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
16
    {
17
        if ($dice === null) {
18
            $dice = new \Dice\Dice();
19
        }
20
21
        if (is_array($json)) {
22
            foreach ($json as $file) {
23
                $dice = $this->load($file, $dice);
24
            }
25
            return $dice;
26
        }
27
28
        if (trim($json)[0] != '{') {
29
            $path = dirname(realpath($json));
30
            $json = str_replace('__DIR__', $path, file_get_contents($json));
31
        }
32
33
        $map = json_decode($json, true);
34
        if (!is_array($map)) {
35
            throw new \Exception('Could not decode json: ' . json_last_error_msg());
36
        }
37
38
        if (isset($map['rules'])) {
39
            foreach ($map['rules'] as $rule) {
40
                $name = $rule['name'];
41
                unset($rule['name']);
42
                $dice->addRule($name, $rule);
43
            }
44
            return $dice;
45
        }
46
47
        foreach ($map as $name => $rule) {
48
            $dice->addRule($name, $rule);
49
        }
50
        return $dice;
51
    }
52
}
53