Passed
Push — hotfix/fix-counts ( b4ff8e...673622 )
by Paul
04:39
created

Template::normalize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 9
ccs 6
cts 7
cp 0.8571
crap 3.0261
rs 10
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'], $path );
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
	 * @param string $templatePath
32
	 * @return string
33
	 */
34 7
	public function interpolate( $template, array $context = [], $templatePath )
35
	{
36 7
		$context = $this->normalizeContext( $context );
37 7
		$context = apply_filters( 'site-reviews/interpolate/'.$templatePath, $context );
38 7
		foreach( $context as $key => $value ) {
39 1
			$template = strtr(
40 1
				$template,
41 1
				array_fill_keys( ['{'.$key.'}', '{{ '.$key.' }}'], $value )
42
			);
43
		}
44 7
		return trim( $template );
45
	}
46
47
	/**
48
	 * @param string $templatePath
49
	 * @return void|string
50
	 */
51
	public function render( $templatePath, array $data = [] )
52
	{
53
		echo $this->build( $templatePath, $data );
54
	}
55
56
	/**
57
	 * @return array
58
	 */
59 7
	protected function normalize( array $data )
60
	{
61 7
		$arrayKeys = ['context', 'globals'];
62 7
		$data = wp_parse_args( $data, array_fill_keys( $arrayKeys, [] ));
63 7
		foreach( $arrayKeys as $key ) {
64 7
			if( is_array( $data[$key] ))continue;
65
			$data[$key] = [];
66
		}
67 7
		return $data;
68
	}
69
70
	/**
71
	 * @return array
72
	 */
73
	protected function normalizeContext( array $context )
74
	{
75 7
		$context = array_filter( $context, function( $value ) {
76 1
			return !is_array( $value ) && !is_object( $value );
77 7
		});
78 7
		return array_map( function( $value ) {
79 1
			return (string)$value;
80 7
		}, $context );
81
	}
82
}
83