VariableResolver::addValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 2
crap 2
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