Passed
Push — master ( decf08...528828 )
by Atanas
02:21
created

View   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 103
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 103
ccs 35
cts 35
cp 1
rs 10
c 0
b 0
f 0
wmc 10
lcom 2
cbo 2

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getGlobals() 0 3 1
A addGlobal() 0 3 1
A addGlobals() 0 5 2
A getComposersForView() 0 11 3
A addComposer() 0 9 1
A compose() 0 13 2
1
<?php
2
3
namespace WPEmerge\View;
4
5
use Closure;
6
use WPEmerge\Helpers\Handler;
7
use WPEmerge\Helpers\Mixed;
8
use WPEmerge\Helpers\Path;
9
use WPEmerge\Support\Arr;
10
11
/**
12
 * Render view files with php
13
 */
14
class View {
15
	/**
16
	 * Global variables
17
	 *
18
	 * @var array
19
	 */
20
	protected $globals = [];
21
22
	/**
23
	 * View composers
24
	 *
25
	 * @var array
26
	 */
27
	protected $composers = [];
28
29
	/**
30
	 * Get global variables
31
	 *
32
	 * @return array
33
	 */
34 2
	public function getGlobals() {
35 2
		return $this->globals;
36
	}
37
38
	/**
39
	 * Set a global variable
40
	 *
41
	 * @param  string $key
42
	 * @param  mixed  $value
43
	 * @return void
44
	 */
45 1
	public function addGlobal( $key, $value ) {
46 1
		$this->globals[ $key ] = $value;
47 1
	}
48
49
	/**
50
	 * Set an array of global variables
51
	 *
52
	 * @param  array $globals
53
	 * @return void
54
	 */
55 1
	public function addGlobals( $globals ) {
56 1
		foreach ( $globals as $key => $value ) {
57 1
			$this->addGlobal( $key, $value );
58 1
		}
59 1
	}
60
61
	/**
62
	 * Get view composer
63
	 *
64
	 * @param  string    $view
65
	 * @return Handler[]
66
	 */
67 1
	public function getComposersForView( $view ) {
68 1
		$composers = [];
69
70 1
		foreach ( $this->composers as $composer ) {
71 1
			if ( in_array( $view, $composer['views'] ) ) {
72 1
				$composers[] = $composer['composer'];
73 1
			}
74 1
		}
75
76 1
		return $composers;
77
	}
78
79
	/**
80
	 * Add view composer
81
	 *
82
	 * @param string|string[] $views
83
	 * @param string|Closure  $composer
84
	 * @return void
85
	 */
86 1
	public function addComposer( $views, $composer ) {
87 1
		$views = Mixed::toArray( $views );
88 1
		$handler = new Handler( $composer );
89
90 1
		$this->composers[] = [
91 1
			'views' => $views,
92 1
			'composer' => $handler,
93
		];
94 1
	}
95
96
	/**
97
	 * Get the composed context for a view.
98
	 * Passes all arguments to the composer.
99
	 *
100
	 * @param  string $view
101
	 * @return array
102
	 */
103 2
	public function compose( $view ) {
104 2
		$context = [];
105 2
		$composers = $this->getComposersForView( $view );
106
107 2
		foreach ( $composers as $composer ) {
108 1
			$context = array_merge(
109 1
				$context,
110 1
				call_user_func_array( [$composer, 'execute'], [$view] )
111 1
			);
112 2
		}
113
114 2
		return $context;
115
	}
116
}
117