1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
namespace Codeception\Util;
/**
* Basic template engine used for generating initial Cept/Cest/Test files.
*/
class Template
{
protected $template;
protected $vars = [];
protected $placeholderStart;
protected $placeholderEnd;
/**
* Takes a template string
*
* @param $template
*/
public function __construct($template, $placeholderStart = '{{', $placeholderEnd = '}}')
{
$this->template = $template;
$this->placeholderStart = $placeholderStart;
$this->placeholderEnd = $placeholderEnd;
}
/**
* Replaces {{var}} string with provided value
*
* @param $var
* @param $val
* @return $this
*/
public function place($var, $val)
{
$this->vars[$var] = $val;
return $this;
}
/**
* Sets all template vars
*
* @param array $vars
*/
public function setVars(array $vars)
{
$this->vars = $vars;
}
/**
* Fills up template string with placed variables.
*
* @return mixed
*/
public function produce()
{
$result = $this->template;
$regex = sprintf('~%s([\w\.]+)%s~m', $this->placeholderStart, $this->placeholderEnd);
$matched = preg_match_all($regex, $result, $matches, PREG_SET_ORDER);
if (!$matched) {
return $result;
}
foreach ($matches as $match) { // fill in placeholders
$placeholder = $match[1];
$value = $this->vars;
foreach (explode('.', $placeholder) as $segment) {
if (is_array($value) && array_key_exists($segment, $value)) {
$value = $value[$segment];
} else {
continue 2;
}
}
$result = str_replace($this->placeholderStart . $placeholder . $this->placeholderEnd, $value, $result);
}
return $result;
}
}