Completed
Push — master ( 134f41...390a97 )
by Daniel
11s
created

AgentFinder::getName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\ObjectAgent;
6
7
class AgentFinder
8
{
9
    private $agents;
10
11
    public function __construct(array $agents)
12
    {
13
        array_map(function (AgentInterface $agent) {
0 ignored issues
show
Unused Code introduced by
The parameter $agent is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
14
        }, $agents);
15
        $this->agents = $agents;
16
    }
17
18
    public function findFor(string $classFqn)
19
    {
20
        foreach ($this->agents as $agent) {
21
            if ($agent->supports($classFqn)) {
22
                return $agent;
23
            }
24
        }
25
26
        $classes = array_map(function ($element) {
27
            return get_class($element);
28
        }, $this->agents);
29
30
        throw new Exception\AgentNotFoundException(sprintf(
31
            'Could not find an agent supporting class "%s". Registered agents: "%s"',
32
            $classFqn, implode('", "', $classes)
33
        ));
34
    }
35
36
    public function get(string $name)
37
    {
38
        if (!isset($this->agents[$name])) {
39
            throw new Exception\AgentNotFoundException(sprintf(
40
                'Could not find an agent named "%s". Registered agent names: "%s"',
41
                $name, implode('", "', array_keys($this->agents))
42
            ));
43
        }
44
45
        return $this->agents[$name];
46
    }
47
48
    public function getName(AgentInterface $unknownAgent)
49
    {
50
        foreach ($this->agents as $name => $agent) {
51
            if ($agent === $unknownAgent) {
52
                return $name;
53
            }
54
        }
55
56
        throw new \RuntimeException(sprintf(
57
            'Could not identify agent of class "%s"',
58
            get_class($unknownAgent)
59
        ));
60
    }
61
}
62