Completed
Push — master ( c49005...51bf9f )
by Bernhard
11:47 queued 08:57
created

LocalUriRetriever::retrieve()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 18
ccs 9
cts 9
cp 1
rs 9.2
cc 4
eloc 9
nc 4
nop 1
crap 4
1
<?php
2
3
/*
4
 * This file is part of the Webmozart JSON package.
5
 *
6
 * (c) Bernhard Schussek <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Webmozart\Json\UriRetriever;
13
14
use JsonSchema\Uri\Retrievers\FileGetContents;
15
use JsonSchema\Uri\Retrievers\UriRetrieverInterface;
16
use Webmozart\PathUtil\Path;
17
18
/**
19
 * @since  1.3
20
 *
21
 * @author Bernhard Schussek <[email protected]>
22
 */
23
class LocalUriRetriever implements UriRetrieverInterface
24
{
25
    /**
26
     * @var string[]
27
     */
28
    private $mappings;
29
30
    /**
31
     * @var string
32
     */
33
    private $baseDir;
34
35
    /**
36
     * @var UriRetrieverInterface
37
     */
38
    private $filesystemRetriever;
39
40
    /**
41
     * @var UriRetrieverInterface
42
     */
43
    private $fallbackRetriever;
44
45
    /**
46
     * @var UriRetrieverInterface
47
     */
48
    private $lastUsedRetriever;
49
50 5
    public function __construct($baseDir = null, array $mappings = array(), UriRetrieverInterface $fallbackRetriever = null)
51
    {
52 5
        $this->baseDir = $baseDir ? Path::canonicalize($baseDir) : null;
53 5
        $this->mappings = $mappings;
54 5
        $this->filesystemRetriever = new FileGetContents();
55 5
        $this->fallbackRetriever = $fallbackRetriever ?: $this->filesystemRetriever;
56 5
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61 4
    public function retrieve($uri)
62
    {
63 4
        if (isset($this->mappings[$uri])) {
64 1
            $uri = $this->mappings[$uri];
65
66 1
            if (Path::isLocal($uri)) {
67 1
                $uri = 'file://'.($this->baseDir ? Path::makeAbsolute($uri, $this->baseDir) : $uri);
68
            }
69
70 1
            $this->lastUsedRetriever = $this->filesystemRetriever;
71
72 1
            return $this->filesystemRetriever->retrieve($uri);
73
        }
74
75 3
        $this->lastUsedRetriever = $this->fallbackRetriever;
76
77 3
        return $this->fallbackRetriever->retrieve($uri);
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 5
    public function getContentType()
84
    {
85 5
        return $this->lastUsedRetriever ? $this->lastUsedRetriever->getContentType() : null;
86
    }
87
}
88