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

ProtocolBasedWriterResolver::resolveWriter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 3
Ratio 27.27 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 3
loc 11
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Alchemy\Zippy\Resource\Resolver;
4
5
use Alchemy\Zippy\Resource\ResourceUri;
6
use Alchemy\Zippy\Resource\ResourceWriter;
7
use Alchemy\Zippy\Resource\ResourceWriterResolver;
8
9
class ProtocolBasedWriterResolver implements ResourceWriterResolver
10
{
11
    /**
12
     * @var ResourceWriter[]
13
     */
14
    private $writers = [];
15
16
    /**
17
     * @var int[] Dictionary of writer indexes, indexed by resource protocol name
18
     */
19
    private $protocolWriterIndexes = [];
20
21
    /**
22
     * @param ResourceWriter $writer
23
     * @param string|string[] $protocols List of compatible protocols
24
     */
25
    public function addWriter(ResourceWriter $writer, $protocols)
26
    {
27
        $protocols = is_array($protocols) ? $protocols : [ $protocols ];
28
        $index = count($this->writers);
29
30
        $this->writers[$index] = $writer;
31
32
        foreach ($protocols as $protocol) {
33
            $this->protocolWriterIndexes[$protocol] = $index;
34
        }
35
    }
36
37
    /**
38
     * Resolves a writer for the given resource URI.
39
     *
40
     * @param ResourceUri $resource
41
     * @return ResourceWriter
42
     */
43
    public function resolveWriter(ResourceUri $resource)
44
    {
45 View Code Duplication
        if (! array_key_exists($resource->getProtocol(), $this->protocolWriterIndexes)) {
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...
46
            throw new \RuntimeException('Unsupported protocol: ' . $resource->getProtocol() . '( ' . $resource  . ')');
47
        }
48
49
        /** @var int $index */
50
        $index = $this->protocolWriterIndexes[$resource->getProtocol()];
51
52
        return $this->writers[$index];
53
    }
54
}
55