Passed
Push — master ( 92d1bc...99b252 )
by Paul
04:41
created

Template::normalizeContext()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 1
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 0
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
	 * @return array
50
	 */
51 7
	protected function normalize( array $data )
52
	{
53 7
		$arrayKeys = ['context', 'globals'];
54 7
		$data = wp_parse_args( $data, array_fill_keys( $arrayKeys, [] ));
55 7
		foreach( $arrayKeys as $key ) {
56 7
			if( is_array( $data[$key] ))continue;
57
			$data[$key] = [];
58
		}
59 7
		return $data;
60
	}
61
62
	/**
63
	 * @return array
64
	 */
65
	protected function normalizeContext( array $context )
66
	{
67 7
		$context = array_filter( $context, function( $value ) {
68 1
			return !is_array( $value ) && !is_object( $value );
69 7
		});
70 7
		return array_map( function( $value ) {
71 1
			return (string)$value;
72 7
		}, $context );
73
	}
74
}
75