Passed
Push — master ( aa9f10...00a0be )
by Atanas
02:02
created

PhpView::toString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
nc 3
nop 0
dl 0
loc 17
ccs 11
cts 11
cp 1
crap 3
rs 9.4285
c 1
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 HasNameTrait, HasContextTrait;
15
16
	/**
17
	 * Filepath to view.
18
	 *
19
	 * @var string
20
	 */
21
	protected $filepath = '';
22
23
	/**
24
	 * Get filepath.
25
	 *
26
	 * @return string
27
	 */
28 1
	public function getFilepath() {
29 1
		return $this->filepath;
30
	}
31
32
	/**
33
	 * Set filepath.
34
	 *
35
	 * @param  string $filepath
36
	 * @return self   $this
37
	 */
38 1
	public function setFilepath( $filepath ) {
39 1
		$this->filepath = $filepath;
40 1
		return $this;
41
	}
42
43
	/**
44
	 * {@inheritDoc}
45
	 */
46 6
	public function toString() {
47 6
		if ( empty( $this->getName() ) ) {
48 1
			throw new Exception( 'View must have a name.' );
49
		}
50
51 5
		if ( empty( $this->getFilepath() ) ) {
52 1
			throw new Exception( 'View must have a filepath.' );
53
		}
54
55 4
		$composed = clone $this;
56 4
		$context = $composed->getContext();
57 4
		$composed->with( ['global' => View::getGlobals()] );
58 4
		View::compose( $composed );
59 4
		$composed->with( $context );
60
61 4
		return $composed->render();
62
	}
63
64
	/**
65
	 * Render the view to string.
66
	 *
67
	 * @return string
68
	 */
69 4
	protected function render() {
70 4
		ob_start();
71 4
		extract( $this->getContext() );
0 ignored issues
show
Bug introduced by
$this->getContext() cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
72 4
		include( $this->getFilepath() );
73 4
		$html = ob_get_clean();
74
75 4
		return $html;
76
	}
77
78
	/**
79
	 * {@inheritDoc}
80
	 */
81 1
	public function toResponse() {
82 1
		return (new Response())
83 1
			->withHeader( 'Content-Type', 'text/html' )
84 1
			->withBody( Psr7\stream_for( $this->toString() ) );
85
	}
86
}
87