VariableResolver   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 12
c 1
b 0
f 0
dl 0
loc 34
ccs 0
cts 21
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A resolve() 0 17 4
A addValue() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Setono\VariableResolver;
6
7
use function Safe\sprintf;
8
use Setono\VariableResolver\Parser\ParserInterface;
9
use Setono\VariableResolver\Variable\Value\ValueInterface;
10
11
final class VariableResolver implements VariableResolverInterface
12
{
13
    /** @var ValueInterface[] */
14
    private array $values = [];
15
16
    private ParserInterface $parser;
17
18
    public function __construct(ParserInterface $parser)
19
    {
20
        $this->parser = $parser;
21
    }
22
23
    public function resolve(string $str): string
24
    {
25
        $variables = $this->parser->parse($str);
26
27
        if (count($variables) === 0) {
28
            return $str;
29
        }
30
31
        foreach ($variables as $variable) {
32
            if (!isset($this->values[$variable->getName()])) {
33
                throw new \InvalidArgumentException(sprintf('The variable, "%s" does not have a corresponding variable value. Please add one.', $variable->getName())); // todo better exception
34
            }
35
36
            $str = str_replace($variable->getValue(), $this->values[$variable->getName()]->getValue(), $str);
37
        }
38
39
        return $str;
40
    }
41
42
    public function addValue(string $variable, ValueInterface $variableValue): void
43
    {
44
        $this->values[$variable] = $variableValue;
45
    }
46
}
47