1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace GeminiLabs\SiteReviews\Modules\Html; |
4
|
|
|
|
5
|
|
|
use GeminiLabs\SiteReviews\Modules\Html; |
6
|
|
|
|
7
|
|
|
class Template |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @param string $templatePath |
11
|
|
|
* @return void|string |
12
|
|
|
*/ |
13
|
7 |
|
public function build( $templatePath, array $data = [] ) |
14
|
|
|
{ |
15
|
7 |
|
$data = $this->normalize( $data ); |
16
|
7 |
|
ob_start(); |
17
|
7 |
|
glsr()->render( $templatePath, $data ); |
18
|
7 |
|
$template = ob_get_clean(); |
19
|
7 |
|
$template = $this->interpolate( $template, $data['context'] ); |
20
|
7 |
|
$template = apply_filters( 'site-reviews/rendered/template', $template, $templatePath, $data ); |
21
|
7 |
|
$template = apply_filters( 'site-reviews/rendered/template/'.$templatePath, $template, $data ); |
22
|
7 |
|
return $template; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Interpolate context values into template placeholders |
27
|
|
|
* @param string $template |
28
|
|
|
* @return string |
29
|
|
|
*/ |
30
|
7 |
|
public function interpolate( $template, array $context = [] ) |
31
|
|
|
{ |
32
|
7 |
|
$context = $this->normalizeContext( $context ); |
33
|
7 |
|
foreach( $context as $key => $value ) { |
34
|
1 |
|
$template = strtr( |
35
|
1 |
|
$template, |
36
|
1 |
|
array_fill_keys( ['{'.$key.'}', '{{ '.$key.' }}'], $value ) |
37
|
|
|
); |
38
|
|
|
} |
39
|
7 |
|
return trim( $template ); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param string $templatePath |
44
|
|
|
* @return void|string |
45
|
|
|
*/ |
46
|
|
|
public function render( $templatePath, array $data = [] ) |
47
|
|
|
{ |
48
|
|
|
echo $this->build( $templatePath, $data ); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @return array |
53
|
|
|
*/ |
54
|
7 |
|
protected function normalize( array $data ) |
55
|
|
|
{ |
56
|
7 |
|
$arrayKeys = ['context', 'globals']; |
57
|
7 |
|
$data = wp_parse_args( $data, array_fill_keys( $arrayKeys, [] )); |
58
|
7 |
|
foreach( $arrayKeys as $key ) { |
59
|
7 |
|
if( is_array( $data[$key] ))continue; |
60
|
|
|
$data[$key] = []; |
61
|
|
|
} |
62
|
7 |
|
return $data; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @return array |
67
|
|
|
*/ |
68
|
|
|
protected function normalizeContext( array $context ) |
69
|
|
|
{ |
70
|
7 |
|
$context = array_filter( $context, function( $value ) { |
71
|
1 |
|
return !is_array( $value ) && !is_object( $value ); |
72
|
7 |
|
}); |
73
|
7 |
|
return array_map( function( $value ) { |
74
|
1 |
|
return (string)$value; |
75
|
7 |
|
}, $context ); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|