Passed
Push — master ( 904eb0...5301fa )
by Atanas
02:22
created

Php::resolveFile()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 9
nc 8
nop 1
dl 0
loc 19
ccs 12
cts 12
cp 1
crap 4
rs 9.2
c 1
b 1
f 0
1
<?php
2
3
namespace WPEmerge\View;
4
5
use View as ViewService;
6
7
/**
8
 * Render view files with php
9
 */
10
class Php implements EngineInterface {
11
	/**
12
	 * {@inheritDoc}
13
	 */
14 1
	public function exists( $view ) {
15 1
		$file = $this->resolveFile( $view );
16 1
		return strlen( $file ) > 0;
17
	}
18
19
	/**
20
	 * {@inheritDoc}
21
	 */
22 1
	public function canonical( $view ) {
23 1
		$file = $this->resolveFile( $view );
24 1
		return $file;
25
	}
26
27
	/**
28
	 * {@inheritDoc}
29
	 */
30 6
	public function render( $views, $context ) {
31 6
		foreach ( $views as $view ) {
32 6
			if ( $this->exists( $view ) ) {
33 5
				$file = $this->resolveFile( $view );
34 5
				return $this->renderView( $view, $file, $context );
35
			}
36 1
		}
37
38 1
		return '';
39
	}
40
41
	/**
42
	 * Render a single view to string
43
	 *
44
	 * @param  string $view
45
	 * @param  string $file
46
	 * @param  array  $context
47
	 * @return string
48
	 */
49 5
	protected function renderView( $view, $file, $context ) {
50 5
		$__file = $file;
51
52 5
		$__context = array_merge(
53 5
			['global' => ViewService::getGlobals()],
54 5
			ViewService::compose( $view ),
55
			$context
56 5
		);
57
58 5
		$renderer = function() use ( $__file, $__context ) {
59 5
			ob_start();
60 5
			extract( $__context );
61 5
			include( $__file );
62 5
			return ob_get_clean();
63 5
		};
64
65 5
		return $renderer();
66
	}
67
68
	/**
69
	 * Resolve a view or a view array to an absolute filepath
70
	 *
71
	 * @param  string $view
72
	 * @return string
73
	 */
74 1
	protected function resolveFile( $view ) {
75 1
		$file = locate_template( $view, false );
76
77 1
		if ( ! $file ) {
78
			// locate_template failed to find the view - try adding a .php extension
79 1
			$file = locate_template( $view . '.php', false );
80 1
		}
81
82 1
		if ( ! $file ) {
83
			// locate_template failed to find the view - test if a valid absolute path was passed
84 1
			$file = $this->resolveFileFromFilesystem( $view );
85 1
		}
86
87 1
		if ( $file ) {
88 1
			$file = realpath( $file );
89 1
		}
90
91 1
		return $file;
92
	}
93
94
	/**
95
	 * Resolve the view if it exists on the filesystem
96
	 *
97
	 * @param  string $view
98
	 * @return string
99
	 */
100 1
	protected function resolveFileFromFilesystem( $view ) {
101 1
		return file_exists( $view ) ? $view : '';
102
	}
103
}
104