Completed
Branch full-rewrite (3b3ffb)
by Thibaud
03:12
created

ProtocolBasedReaderResolver::addFactory()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 3
eloc 6
nc 4
nop 2
1
<?php
2
3
namespace Alchemy\Zippy\Resource\Resolver;
4
5
use Alchemy\Zippy\Resource\ResourceReader;
6
use Alchemy\Zippy\Resource\ResourceReaderFactory;
7
use Alchemy\Zippy\Resource\ResourceReaderResolver;
8
use Alchemy\Zippy\Resource\ResourceUri;
9
10
class ProtocolBasedReaderResolver implements ResourceReaderResolver
11
{
12
    /**
13
     * @var ResourceReaderFactory[]
14
     */
15
    private $factories = [];
16
17
    /**
18
     * @var int[] Dictionary of factory indexes, indexed by resource protocol name
19
     */
20
    private $protocolFactoryIndexes = [];
21
22
    /**
23
     * @param ResourceReaderFactory $factory
24
     * @param string|string[] $protocols List of compatible protocols
25
     */
26
    public function addFactory(ResourceReaderFactory $factory, $protocols)
27
    {
28
        $protocols = is_array($protocols) ? $protocols : [ $protocols ];
29
        $index = count($this->factories);
30
31
        $this->factories[$index] = $factory;
32
33
        foreach ($protocols as $protocol) {
34
            $this->protocolFactoryIndexes[$protocol] = (int) $index;
35
        }
36
    }
37
38
    /**
39
     * Resolves a reader for the given resource URI.
40
     *
41
     * @param ResourceUri $resource
42
     * @return ResourceReader
43
     */
44
    public function resolveReader(ResourceUri $resource)
45
    {
46 View Code Duplication
        if (! array_key_exists($resource->getProtocol(), $this->protocolFactoryIndexes)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
47
            throw new \RuntimeException('Unsupported protocol: ' . $resource->getProtocol() . '( ' . $resource  . ')');
48
        }
49
50
        /** @var int $index */
51
        $index = $this->protocolFactoryIndexes[$resource->getProtocol()];
52
        /** @var ResourceReaderFactory $factory */
53
        $factory = $this->factories[$index];
54
55
        return $factory->createReaderFor($resource);
56
    }
57
}
58