Test Failed
Push — hotfix/fix-counts ( e9420b...4803a6 )
by Paul
05:49
created

Template   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Test Coverage

Coverage 74.29%

Importance

Changes 5
Bugs 0 Features 3
Metric Value
eloc 30
c 5
b 0
f 3
dl 0
loc 73
ccs 26
cts 35
cp 0.7429
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 12 1
A interpolate() 0 11 2
A render() 0 3 1
A normalize() 0 9 3
A normalizeContext() 0 8 2
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 5
	public function build( $templatePath, array $data = [] )
15
	{
16 5
		$data = $this->normalize( $data );
17 5
		ob_start();
18 5
		glsr()->render( $templatePath, $data );
19 5
		$template = ob_get_clean();
20 5
		$path = glsr( Helper::class )->removePrefix( 'templates/', $templatePath );
21 5
		$template = apply_filters( 'site-reviews/build/template/'.$path, $template, $data );
22 5
		$template = $this->interpolate( $template, $data['context'], $path );
23 5
		$template = apply_filters( 'site-reviews/rendered/template', $template, $templatePath, $data );
24 5
		$template = apply_filters( 'site-reviews/rendered/template/'.$path, $template, $data );
25 5
		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 5
	public function interpolate( $template, array $context = [], $templatePath )
35
	{
36 5
		$context = $this->normalizeContext( $context );
37 5
		$context = apply_filters( 'site-reviews/interpolate/'.$templatePath, $context );
38 5
		foreach( $context as $key => $value ) {
39
			$template = strtr(
40
				$template,
41
				array_fill_keys( ['{'.$key.'}', '{{ '.$key.' }}'], $value )
42
			);
43
		}
44 5
		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 5
	protected function normalize( array $data )
60
	{
61 5
		$arrayKeys = ['context', 'globals'];
62 5
		$data = wp_parse_args( $data, array_fill_keys( $arrayKeys, [] ));
63 5
		foreach( $arrayKeys as $key ) {
64 5
			if( is_array( $data[$key] ))continue;
65
			$data[$key] = [];
66
		}
67 5
		return $data;
68
	}
69
70
	/**
71
	 * @return array
72
	 */
73
	protected function normalizeContext( array $context )
74
	{
75 5
		$context = array_filter( $context, function( $value ) {
76
			return !is_array( $value ) && !is_object( $value );
77 5
		});
78 5
		return array_map( function( $value ) {
79
			return (string)$value;
80 5
		}, $context );
81
	}
82
}
83