Passed
Push — master ( dc3967...a95317 )
by Paul
07:16
created

Template   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Test Coverage

Coverage 74.29%

Importance

Changes 0
Metric Value
dl 0
loc 78
ccs 26
cts 35
cp 0.7429
rs 10
c 0
b 0
f 0
wmc 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 7 1
A interpolate() 0 10 2
A renderSettingFields() 0 5 1
A render() 0 3 1
A normalize() 0 10 3
A normalizeContext() 0 8 2
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
		return $this->interpolate( $template, $data['context'] );
20
	}
21
22
	/**
23
	 * Interpolate context values into template placeholders
24
	 * @param string $template
25
	 * @return string
26
	 */
27 7
	public function interpolate( $template, array $context = [] )
28
	{
29 7
		$context = $this->normalizeContext( $context );
30 7
		foreach( $context as $key => $value ) {
31 1
			$template = strtr(
32 1
				$template,
33 1
				array_fill_keys( ['{'.$key.'}', '{{ '.$key.' }}'], $value )
34
			);
35
		}
36 7
		return trim( $template );
37
	}
38
39
	/**
40
	 * @param string $templatePath
41
	 * @return void|string
42
	 */
43
	public function render( $templatePath, array $data = [] )
44
	{
45
		echo $this->build( $templatePath, $data );
46
	}
47
48
	/**
49
	 * @param string $id
50
	 * @return void
51
	 */
52
	public function renderSettingFields( $id )
53
	{
54
		$rows = $this->build( 'pages/settings/'.$id, [
0 ignored issues
show
Unused Code introduced by
The assignment to $rows is dead and can be removed.
Loading history...
55
		]);
56
		glsr_debug( $id );
57
	}
58
59
	/**
60
	 * @return array
61
	 */
62 7
	protected function normalize( array $data )
63
	{
64 7
		$data = wp_parse_args( $data, array_fill_keys( ['context', 'globals'], [] ));
65 7
		foreach( $data as $key => $value ) {
66 7
			if( is_array( $value ))continue;
67
			$data[$key] = [];
68
		}
69 7
		$data['template'] = $this;
70 7
		$data['render'] = glsr( Html::class )->render( $data['globals'] );
71 7
		return $data;
72
	}
73
74
	/**
75
	 * @return array
76
	 */
77
	protected function normalizeContext( array $context )
78
	{
79 7
		$context = array_filter( $context, function( $value ) {
80 1
			return !is_array( $value ) && !is_object( $value );
81 7
		});
82 7
		return array_map( function( $value ) {
83 1
			return esc_attr( (string)$value );
84 7
		}, $context );
85
	}
86
}
87