Completed
Push — master ( c762b0...684d44 )
by John
02:56
created

DefinitionLoader   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 7
dl 0
loc 44
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 3
A load() 0 14 3
1
<?php declare(strict_types = 1);
2
/*
3
 * This file is part of the KleijnWeb\ApiDescriptions package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\ApiDescriptions\Description\Document\Definition\Loader;
10
11
use KleijnWeb\ApiDescriptions\Description\Document\Parser\JsonParser;
12
use KleijnWeb\ApiDescriptions\Description\Document\Parser\Parser;
13
use KleijnWeb\ApiDescriptions\Description\Document\Parser\YamlParser;
14
use KleijnWeb\ApiDescriptions\Description\Document\Reader\Reader;
15
use KleijnWeb\ApiDescriptions\Description\Document\Reader\SimpleReader;
16
17
/**
18
 * @author John Kleijn <[email protected]>
19
 */
20
class DefinitionLoader
21
{
22
    /**
23
     * @var Parser[]
24
     */
25
    private $parsers;
26
27
    /**
28
     * @var Reader
29
     */
30
    private $reader;
31
32
    /**
33
     * DefinitionLoader constructor.
34
     *
35
     * @param Reader   $reader
36
     * @param Parser[] $parsers
37
     */
38
    public function __construct(Reader $reader = null, Parser ...$parsers)
39
    {
40
        $this->reader  = $reader ?: new SimpleReader();
41
        $this->parsers = $parsers ?: [new JsonParser(), new YamlParser()];
42
    }
43
44
    /**
45
     * @param string $uri
46
     *
47
     * @return \stdClass
48
     */
49
    public function load(string $uri): \stdClass
50
    {
51
        $response = $this->reader->read($uri);
52
53
        foreach ($this->parsers as $parser) {
54
            if (!$parser->canParse($response->getContentType())) {
55
                continue;
56
            }
57
58
            return $parser->parse($response->getContent());
59
        }
60
61
        throw new ResourceNotParsableException("No parser for response of '$uri''");
62
    }
63
}
64