This repository has been archived by the owner on Mar 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
PhpView.php
75 lines (67 loc) · 1.71 KB
/
PhpView.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
namespace Wandu\View;
use Exception;
use Throwable;
use Wandu\View\Contracts\RenderInterface;
class PhpView implements RenderInterface
{
/** @var string */
protected $basePath;
/** @var array */
protected $values = [];
/**
* @param string $basePath
*/
public function __construct($basePath = '')
{
$this->basePath = $basePath;
}
/**
* {@inheritdoc}
*/
public function with(array $values = [])
{
$new = clone $this;
$new->values = $values;
return $new;
}
/**
* {@inheritdoc}
*/
public function render($template, array $values = [], $basePath = null)
{
if (!isset($basePath)) {
$basePath = $this->basePath;
}
if (!file_exists("{$basePath}/{$template}")) {
throw new FileNotFoundException("Cannot find the file, {$basePath}/{$template}");
}
$values = $values + $this->values;
$_startObLevel = ob_get_level();
ob_start();
extract($values);
try {
require "{$basePath}/{$template}";
} catch (Exception $e) {
$this->cleanOutputBuffer($_startObLevel);
throw $e;
} catch (Throwable $e) {
$this->cleanOutputBuffer($_startObLevel);
throw $e;
}
return $this->cleanOutputBuffer($_startObLevel);
}
/**
* @param int $startObLevel
* @return string
*/
protected function cleanOutputBuffer($startObLevel)
{
$contents = '';
while (ob_get_level() - $startObLevel > 0) {
$contents = ob_get_contents() . $contents;
ob_end_clean();
}
return $contents;
}
}