Passed
Push — master ( f2f9a5...aa567c )
by Atanas
01:53
created

PhpView::toResponse()   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 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace WPEmerge\View;
4
5
use Exception;
6
use GuzzleHttp\Psr7;
7
use GuzzleHttp\Psr7\Response;
8
use WPEmerge\Facades\View;
9
10
/**
11
 * Render a view file with php.
12
 */
13
class PhpView implements ViewInterface {
14
	use HasContextTrait;
15
16
	/**
17
	 * View name.
18
	 *
19
	 * @var string
20
	 */
21
	protected $name = '';
22
23
	/**
24
	 * Filepath to view.
25
	 *
26
	 * @var string
27
	 */
28
	protected $filepath = '';
29
30
	/**
31
	 * {@inheritDoc}
32
	 */
33 1
	public function getName() {
34 1
		return $this->name;
35
	}
36
37
	/**
38
	 * {@inheritDoc}
39
	 */
40 1
	public function setName( $name ) {
41 1
		$this->name = $name;
42 1
		return $this;
43
	}
44
45
	/**
46
	 * Get filepath.
47
	 *
48
	 * @return string
49
	 */
50 1
	public function getFilepath() {
51 1
		return $this->filepath;
52
	}
53
54
	/**
55
	 * Set filepath.
56
	 *
57
	 * @param  string $filepath
58
	 * @return self   $this
59
	 */
60 1
	public function setFilepath( $filepath ) {
61 1
		$this->filepath = $filepath;
62 1
		return $this;
63
	}
64
65
	/**
66
	 * {@inheritDoc}
67
	 */
68 7
	public function toString() {
69 7
		if ( empty( $this->getName() ) ) {
70 1
			throw new Exception( 'View must have a name.' );
71
		}
72
73 6
		if ( empty( $this->getFilepath() ) ) {
74 1
			throw new Exception( 'View must have a filepath.' );
75
		}
76
77 5
		$global_context = ['global' => View::getGlobals()];
78 5
		$local_context = $this->getContext();
79
80 5
		$this->with( $global_context );
81 5
		View::compose( $this );
82 5
		$this->with( $local_context );
83
84 5
		$renderer = function() {
85 5
			ob_start();
86 5
			$__context = $this->getContext();
87 5
			extract( $__context );
88 5
			include( $this->getFilepath() );
89 5
			return ob_get_clean();
90 5
		};
91
92 5
		return $renderer();
93
	}
94
95
	/**
96
	 * {@inheritDoc}
97
	 */
98 1
	public function toResponse() {
99 1
		return (new Response())
100 1
			->withHeader( 'Content-Type', 'text/html' )
101 1
			->withBody( Psr7\stream_for( $this->toString() ) );
102
	}
103
}
104