Passed
Push — master ( 648c0b...8eca98 )
by Paul
09:10
created

Template::build()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 1

Importance

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