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\ResourceReader; |
15
|
|
|
use Alchemy\Resource\ResourceReaderFactory; |
16
|
|
|
use Alchemy\Resource\ResourceReaderResolver; |
17
|
|
|
use Alchemy\Resource\ResourceUri; |
18
|
|
|
|
19
|
|
|
class ProtocolBasedReaderResolver implements ResourceReaderResolver |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var ResourceReaderFactory[] |
23
|
|
|
*/ |
24
|
|
|
private $factories = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var int[] Dictionary of factory indexes, indexed by resource protocol name |
28
|
|
|
*/ |
29
|
|
|
private $protocolFactoryIndexes = []; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param ResourceReaderFactory $factory |
33
|
|
|
* @param string|string[] $protocols List of compatible protocols |
34
|
|
|
*/ |
35
|
4 |
View Code Duplication |
public function addFactory(ResourceReaderFactory $factory, $protocols) |
|
|
|
|
36
|
|
|
{ |
37
|
4 |
|
$protocols = is_array($protocols) ? $protocols : [ $protocols ]; |
38
|
4 |
|
$index = count($this->factories); |
39
|
|
|
|
40
|
4 |
|
$this->factories[$index] = $factory; |
41
|
|
|
|
42
|
4 |
|
foreach ($protocols as $protocol) { |
43
|
4 |
|
$this->protocolFactoryIndexes[$protocol] = (int) $index; |
44
|
3 |
|
} |
45
|
4 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Resolves a reader for the given resource URI. |
49
|
|
|
* |
50
|
|
|
* @param ResourceUri $resource |
51
|
|
|
* @return ResourceReader |
52
|
|
|
*/ |
53
|
8 |
|
public function resolveReader(ResourceUri $resource) |
54
|
|
|
{ |
55
|
8 |
View Code Duplication |
if (! array_key_exists($resource->getProtocol(), $this->protocolFactoryIndexes)) { |
|
|
|
|
56
|
4 |
|
throw new \RuntimeException('Unsupported protocol: ' . $resource->getProtocol() . '( ' . $resource . ')'); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** @var int $factoryIndex */ |
60
|
4 |
|
$factoryIndex = $this->protocolFactoryIndexes[$resource->getProtocol()]; |
61
|
|
|
/** @var ResourceReaderFactory $factory */ |
62
|
4 |
|
$factory = $this->factories[$factoryIndex]; |
63
|
|
|
|
64
|
4 |
|
return $factory->createReaderFor($resource); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
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.