Completed
Push — master ( 10273b...44c8cc )
by Michael
02:31
created

Renderer::getValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Schnittstabil\Curty;
4
5
use Closure;
6
use Schnittstabil\Get;
7
8
/**
9
 * Curty micro templating renderer.
10
 *
11
 * @internal
12
 */
13
class Renderer
14
{
15
    /**
16
     * Render template until a fixed point is reached.
17
     *
18
     * @param string       $tpl Curty template
19
     * @param object|array $ctx Context (variable lookup table)
20
     *
21
     * @return string
22
     */
23
    public function __invoke(string $tpl, $ctx) : string
24
    {
25
        do {
26
            $old = $tpl;
27
            $tpl = $this->render($tpl, $ctx);
28
        } while ($tpl !== $old);
29
30
        return $tpl;
31
    }
32
33
    /**
34
     * Render template.
35
     *
36
     * @param string       $tpl Curty template
37
     * @param object|array $ctx Context (variable lookup table)
38
     *
39
     * @return string
40
     */
41
    public function render(string $tpl, $ctx) : string
42
    {
43
        if (!preg_match_all('/{{([^{]+?)}}/', $tpl, $matches)) {
44
            return $tpl;
45
        }
46
47
        foreach ($matches[1] as $key) {
48
            try {
49
                $replace = $this->getValue($key, $ctx);
50
            } catch (\Schnittstabil\Get\OutOfBoundsException $e) {
51
                continue;
52
            }
53
54
            $tpl = str_replace('{{'.$key.'}}', $this->renderValue($replace), $tpl);
55
        }
56
57
        return $tpl;
58
    }
59
60
    protected function getValue(string $key, $ctx)
61
    {
62
        $value = Get\valueOrFail($key, $ctx);
63
64
        if ($value instanceof Closure) {
65
            return $value();
66
        }
67
68
        return $value;
69
    }
70
71
    protected function renderValue($value) : string
72
    {
73
        if (is_bool($value)) {
74
            return var_export($value, true);
75
        }
76
77
        if (is_scalar($value) || method_exists($value, '__toString')) {
78
            return (string) $value;
79
        }
80
81
        return @json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION);
82
    }
83
}
84