|
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() ); |
|
|
|
|
|
|
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
|
|
|
|