Test Failed
Push — master ( 73b77e...92d1bc )
by Paul
04:01
created

Template   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 68.97%

Importance

Changes 0
Metric Value
dl 0
loc 66
ccs 20
cts 29
cp 0.6897
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 7 1
A render() 0 3 1
A normalize() 0 9 3
A interpolate() 0 10 2
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 6
	public function build( $templatePath, array $data = [] )
14
	{
15 6
		$data = $this->normalize( $data );
16 6
		ob_start();
17 6
		glsr()->render( $templatePath, $data );
18 6
		$template = ob_get_clean();
19 6
		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 6
	public function interpolate( $template, array $context = [] )
28
	{
29 6
		$context = $this->normalizeContext( $context );
30 6
		foreach( $context as $key => $value ) {
31
			$template = strtr(
32
				$template,
33
				array_fill_keys( ['{'.$key.'}', '{{ '.$key.' }}'], $value )
34
			);
35
		}
36 6
		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
	 * @return array
50
	 */
51 6
	protected function normalize( array $data )
52
	{
53 6
		$arrayKeys = ['context', 'globals'];
54 6
		$data = wp_parse_args( $data, array_fill_keys( $arrayKeys, [] ));
55 6
		foreach( $arrayKeys as $key ) {
56 6
			if( is_array( $data[$key] ))continue;
57
			$data[$key] = [];
58
		}
59 6
		return $data;
60
	}
61
62
	/**
63
	 * @return array
64
	 */
65
	protected function normalizeContext( array $context )
66
	{
67 6
		$context = array_filter( $context, function( $value ) {
68
			return !is_array( $value ) && !is_object( $value );
69 6
		});
70 6
		return array_map( function( $value ) {
71
			return (string)$value;
72 6
		}, $context );
73
	}
74
}
75