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

ProtocolBasedWriterResolver   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 6.52 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
c 1
b 0
f 0
lcom 1
cbo 1
dl 3
loc 46
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A addWriter() 0 11 3
A resolveWriter() 3 11 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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