Completed
Push — master ( 1ece6c...656998 )
by Jan Philipp
13s queued 11s
created

TemplateEngine::render()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 3
nc 4
nop 2
1
<?php declare(strict_types=1);
2
3
4
namespace Shopware\Psh\ScriptRuntime\Execution;
5
6
/**
7
 * Replace the placeholders with there values
8
 */
9
class TemplateEngine
10
{
11
    const REGEX = '/__[A-Z0-9,_,-]+?__(?!\(sic\!\))/';
12
13
    const REGEX_SIC = '/__[A-Z0-9,_,-]+?__(\(sic\!\))/';
14
15
    /**
16
     * @param string $shellCommand
17
     * @param ValueProvider[] $allValues
18
     * @return string
19
     */
20
    public function render(string $shellCommand, array $allValues): string
21
    {
22
        preg_match_all(self::REGEX, $shellCommand, $matches);
23
        $placeholders = $matches[0];
24
25
        foreach ($placeholders as $match) {
26
            $shellCommand = str_replace($match, $this->getValue($match, $allValues), $shellCommand);
27
        }
28
29
        preg_match_all(self::REGEX_SIC, $shellCommand, $matches);
30
        $escapedPlaceholders = $matches[0];
31
32
        foreach ($escapedPlaceholders as $match) {
33
            $shellCommand = str_replace($match, str_replace('(sic!)', '', $match), $shellCommand);
34
        }
35
36
        return $shellCommand;
37
    }
38
39
    /**
40
     * @param string $placeholder
41
     * @param array $allValues
42
     * @return mixed
43
     * @throws \RuntimeException
44
     */
45
    private function getValue(string $placeholder, array $allValues)
46
    {
47
        $valueName = substr($placeholder, 2, -2);
48
49
        foreach (array_keys($allValues) as $key) {
50
            if (strtoupper($key) === $valueName) {
51
                return $allValues[$key]->getValue();
52
            }
53
        }
54
55
        throw new \RuntimeException('Missing required value for "' . $valueName . '"');
56
    }
57
}
58