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

Template::normalizeContext()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 8
ccs 4
cts 6
cp 0.6667
crap 2.1481
rs 10
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