Passed
Push — master ( a8bd8b...f2f9a5 )
by Atanas
02:01
created

NameProxyViewEngine::canonical()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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