Passed
Branch feature/first-release (f6e752)
by Andrea Marco
02:33
created

Source   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 18
c 1
b 0
f 0
dl 0
loc 66
ccs 0
cts 10
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getIterator() 0 3 1
A toTraversable() 0 11 3
A __construct() 0 3 1
1
<?php
2
3
namespace Cerbero\LazyJson;
4
5
use Cerbero\LazyJson\Exceptions\LazyJsonException;
6
use Cerbero\LazyJson\Handlers;
7
use IteratorAggregate;
8
use Traversable;
9
10
/**
11
 * The JSON source.
12
 *
13
 */
14
class Source implements IteratorAggregate
15
{
16
    /**
17
     * The traversable JSON.
18
     *
19
     * @var Traversable
20
     */
21
    protected $traversable;
22
23
    /**
24
     * The source handlers.
25
     *
26
     * @var Handlers\AbstractHandler[]
27
     */
28
    protected $handlers = [
29
        Handlers\Endpoint::class,
30
        Handlers\Filename::class,
31
        Handlers\JsonString::class,
32
        Handlers\IterableSource::class,
33
        Handlers\LaravelClientResponse::class,
34
        Handlers\Psr7Message::class,
35
        Handlers\Psr7Stream::class,
36
        Handlers\Resource::class,
37
    ];
38
39
    /**
40
     * Instantiate the class.
41
     *
42
     * @param mixed $source
43
     * @param string $path
44
     */
45
    public function __construct($source, string $path)
46
    {
47
        $this->traversable = $this->toTraversable($source, $path);
48
    }
49
50
    /**
51
     * Turn the given JSON source into a traversable instance
52
     *
53
     * @param mixed $source
54
     * @param string $path
55
     * @return Traversable
56
     *
57
     * @throws LazyJsonException
58
     */
59
    protected function toTraversable($source, string $path): Traversable
60
    {
61
        foreach ($this->handlers as $handler) {
62
            $result = $handler::of($source, $path)->handle();
63
64
            if ($result instanceof Traversable) {
65
                return $result;
66
            }
67
        }
68
69
        throw new LazyJsonException('Unable to load the JSON from the provided source.');
70
    }
71
72
    /**
73
     * Retrieve the traversable JSON
74
     *
75
     * @return Traversable
76
     */
77
    public function getIterator(): Traversable
78
    {
79
        return $this->traversable;
80
    }
81
}
82