Passed
Push — master ( c79e5e...e26cd8 )
by Paul
04:29
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
		$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