1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of alchemy/resource-component. |
5
|
|
|
* |
6
|
|
|
* (c) Alchemy <[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 Alchemy\Resource\Resolver; |
13
|
|
|
|
14
|
|
|
use Alchemy\Resource\ResourceUri; |
15
|
|
|
use Alchemy\Resource\ResourceWriter; |
16
|
|
|
use Alchemy\Resource\ResourceWriterResolver; |
17
|
|
|
|
18
|
|
|
class ProtocolBasedWriterResolver implements ResourceWriterResolver |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var ResourceWriter[] |
22
|
|
|
*/ |
23
|
|
|
private $writers = []; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var int[] Dictionary of writer indexes, indexed by resource protocol name |
27
|
|
|
*/ |
28
|
|
|
private $protocolWriterIndexes = []; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param ResourceWriter $writer |
32
|
|
|
* @param string|string[] $protocols List of compatible protocols |
33
|
|
|
*/ |
34
|
4 |
View Code Duplication |
public function addWriter(ResourceWriter $writer, $protocols) |
|
|
|
|
35
|
|
|
{ |
36
|
4 |
|
$protocols = is_array($protocols) ? $protocols : [ $protocols ]; |
37
|
4 |
|
$index = count($this->writers); |
38
|
|
|
|
39
|
4 |
|
$this->writers[$index] = $writer; |
40
|
|
|
|
41
|
4 |
|
foreach ($protocols as $protocol) { |
42
|
4 |
|
$this->protocolWriterIndexes[$protocol] = $index; |
43
|
3 |
|
} |
44
|
4 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Resolves a writer for the given resource URI. |
48
|
|
|
* |
49
|
|
|
* @param ResourceUri $resource |
50
|
|
|
* @return ResourceWriter |
51
|
|
|
*/ |
52
|
8 |
|
public function resolveWriter(ResourceUri $resource) |
53
|
|
|
{ |
54
|
8 |
View Code Duplication |
if (! array_key_exists($resource->getProtocol(), $this->protocolWriterIndexes)) { |
|
|
|
|
55
|
4 |
|
throw new \RuntimeException('Unsupported protocol: ' . $resource->getProtocol() . '( ' . $resource . ')'); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** @var int $index */ |
59
|
4 |
|
$index = $this->protocolWriterIndexes[$resource->getProtocol()]; |
60
|
|
|
|
61
|
4 |
|
return $this->writers[$index]; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
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.