Passed
Push — master ( c89772...da5ca0 )
by Atanas
01:54
created

NameProxyViewEngine::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace WPEmerge\View;
4
5
use WPEmerge\Facades\Framework;
6
7
/**
8
 * Render view files with different engines depending on their filename
9
 */
10
class NameProxyViewEngine implements ViewEngineInterface {
11
	/**
12
	 * Container key of default engine to use
13
	 *
14
	 * @var string
15
	 */
16
	protected $default = WPEMERGE_VIEW_PHP_VIEW_ENGINE_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
	public function __construct( $bindings, $default = '' ) {
32
		$this->bindings = $bindings;
33
34
		if ( ! empty( $default ) ) {
35
			$this->default = $default;
36
		}
37
	}
38
39
	/**
40
	 * {@inheritDoc}
41
	 */
42
	public function exists( $view ) {
43
		$engine_key = $this->getBindingForFile( $view );
44
		$engine = Framework::resolve( $engine_key );
45
		return $engine->exists( $view );
46
	}
47
48
	/**
49
	 * {@inheritDoc}
50
	 */
51
	public function canonical( $view ) {
52
		$engine_key = $this->getBindingForFile( $view );
53
		$engine = Framework::resolve( $engine_key );
54
		return $engine->canonical( $view );
55
	}
56
57
	/**
58
	 * {@inheritDoc}
59
	 * @throws ViewNotFoundException
60
	 */
61
	public function make( $views ) {
62
		foreach ( $views as $view ) {
63
			if ( $this->exists( $view ) ) {
64
				$engine_key = $this->getBindingForFile( $view );
65
				$engine = Framework::resolve( $engine_key );
66
				return $engine->make( [$view] );
67
			}
68
		}
69
70
		throw new ViewNotFoundException( 'View not found for "' . implode( ', ', $views ) . '"' );
71
	}
72
73
	/**
74
	 * Get the default binding
75
	 *
76
	 * @return string $binding
77
	 */
78
	public function getDefaultBinding() {
79
		return $this->default;
80
	}
81
82
	/**
83
	 * Get all bindings
84
	 *
85
	 * @return array  $bindings
86
	 */
87
	public function getBindings() {
88
		return $this->bindings;
89
	}
90
91
	/**
92
	 * Get the engine key binding for a specific file
93
	 *
94
	 * @param  string $file
95
	 * @return string
96
	 */
97
	public function getBindingForFile( $file ) {
98
		$engine_key = $this->default;
99
100
		foreach ( $this->bindings as $suffix => $engine ) {
101
			if ( substr( $file, -strlen( $suffix ) ) === $suffix ) {
102
				$engine_key = $engine;
103
				break;
104
			}
105
		}
106
107
		return $engine_key;
108
	}
109
}
110