Passed
Push — master ( 11c67b...955441 )
by Atanas
02:20
created

FilenameProxy::getBindingForFile()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace WPEmerge\View;
4
5
use WPEmerge;
6
7
/**
8
 * Render view files with different engines depending on their filename
9
 */
10
class FilenameProxy implements \WPEmerge\View\EngineInterface {
11
	/**
12
	 * Container key of default engine to use
13
	 *
14
	 * @var string
15
	 */
16
	protected $default = WPEMERGE_VIEW_ENGINE_PHP_KEY;
17
18
	/**
19
	 * Array of filename_suffix=>engine_container_key bindings
20
	 *
21
	 * @var array
22
	 */
23
	protected $bindings = [];
24
25
	/**
26
	 * Constructor
27
	 *
28
	 * @param array  $bindings
29
	 * @param string $default
30
	 */
31 3
	public function __construct( $bindings, $default = '' ) {
32 3
		$this->bindings = $bindings;
33
34 3
		if ( ! empty( $default ) ) {
35 1
			$this->default = $default;
36 1
		}
37 3
	}
38
39
	/**
40
	 * {@inheritDoc}
41
	 */
42 1
	public function exists( $view ) {
43 1
		$engine_key = $this->getBindingForFile( $view );
44 1
		$engine_instance = WPEmerge::resolve( $engine_key );
45 1
		return $engine_instance->exists( $view );
46
	}
47
48
	/**
49
	 * {@inheritDoc}
50
	 */
51 1
	public function render( $views, $context ) {
52 1
		foreach ( $views as $view ) {
53 1
			if ( $this->exists( $view ) ) {
54 1
				$engine_key = $this->getBindingForFile( $view );
55 1
				$engine_instance = WPEmerge::resolve( $engine_key );
56 1
				return $engine_instance->render( [$view], $context );
57
			}
58
		}
59
60
		return '';
61
	}
62
63
	/**
64
	 * Get the default binding
65
	 *
66
	 * @return string $binding
67
	 */
68 2
	public function getDefaultBinding() {
69 2
		return $this->default;
70
	}
71
72
	/**
73
	 * Get all bindings
74
	 *
75
	 * @return array  $bindings
76
	 */
77 1
	public function getBindings() {
78 1
		return $this->bindings;
79
	}
80
81
	/**
82
	 * Get the engine key binding for a specific file
83
	 *
84
	 * @param  string $file
85
	 * @return string
86
	 */
87 1
	public function getBindingForFile( $file ) {
88 1
		$engine_key = $this->default;
89
90 1
		foreach ( $this->bindings as $suffix => $engine ) {
91 1
			if ( substr( $file, -strlen( $suffix ) ) === $suffix ) {
92 1
				$engine_key = $engine;
93 1
				break;
94
			}
95 1
		}
96
97 1
		return $engine_key;
98
	}
99
}
100