<?php<liu21st@gmail.com>
namespace think\view\driver;
use think\App;
use think\exception\TemplateNotFoundException;
use think\Loader;
use think\Log;
use think\Request;
class Php
{
protected $config = [
'view_base' => '',
'view_path' => '',
'view_suffix' => 'php',
'view_depr' => DS,
'auto_rule' => 1,
];
protected $template;
protected $content;
public function __construct($config = [])
{
$this->config = array_merge($this->config, $config);
}
public function exists($template)
{
if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
$template = $this->parseTemplate($template);
}
return is_file($template);
}
public function fetch($template, $data = [])
{
if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
$template = $this->parseTemplate($template);
}
if (!is_file($template)) {
throw new TemplateNotFoundException('template not exists:' . $template, $template);
}
$this->template = $template;
App::$debug && Log::record('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]', 'info');
extract($data, EXTR_OVERWRITE);
include $this->template;
}
public function display($content, $data = [])
{
$this->content = $content;
extract($data, EXTR_OVERWRITE);
eval('?>' . $this->content);
}
private function parseTemplate($template)
{
if (empty($this->config['view_path'])) {
$this->config['view_path'] = App::$modulePath . 'view' . DS;
}
$request = Request::instance();
if (strpos($template, '@')) {
list($module, $template) = explode('@', $template);
}
if ($this->config['view_base']) {
$module = isset($module) ? $module : $request->module();
$path = $this->config['view_base'] . ($module ? $module . DS : '');
} else {
$path = isset($module) ? APP_PATH . $module . DS . 'view' . DS : $this->config['view_path'];
}
$depr = $this->config['view_depr'];
if (0 !== strpos($template, '/')) {
$template = str_replace(['/', ':'], $depr, $template);
$controller = Loader::parseName($request->controller());
if ($controller) {
if ('' == $template) {
$template = str_replace('.', DS, $controller) . $depr . (1 == $this->config['auto_rule'] ? Loader::parseName($request->action(true)) : $request->action());
} elseif (false === strpos($template, $depr)) {
$template = str_replace('.', DS, $controller) . $depr . $template;
}
}
} else {
$template = str_replace(['/', ':'], $depr, substr($template, 1));
}
return $path . ltrim($template, '/') . '.' . ltrim($this->config['view_suffix'], '.');
}
public function config($name, $value = null)
{
if (is_array($name)) {
$this->config = array_merge($this->config, $name);
} elseif (is_null($value)) {
return isset($this->config[$name]) ? $this->config[$name] : null;
} else {
$this->config[$name] = $value;
}
}
}