<?php<liu21st@gmail.com>
namespace think\view\driver;
use think\Container;
use think\exception\TemplateNotFoundException;
use think\Loader;
class Php
{
protected $config = [
'view_base' => '',
'view_path' => '',
'view_suffix' => 'php',
'view_depr' => DIRECTORY_SEPARATOR,
];
public function __construct($config = [])
{
$this->config = array_merge($this->config, (array) $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);
}
Container::get('app')
->log('[ VIEW ] ' . $template . ' [ ' . var_export(array_keys($data), true) . ' ]');
if (isset($data['template'])) {
$__template__ = $template;
extract($data, EXTR_OVERWRITE);
include $__template__;
} else {
extract($data, EXTR_OVERWRITE);
include $template;
}
}
public function display($content, $data = [])
{
if (isset($data['content'])) {
$__content__ = $content;
extract($data, EXTR_OVERWRITE);
eval('?>' . $__content__);
} else {
extract($data, EXTR_OVERWRITE);
eval('?>' . $content);
}
}
private function parseTemplate($template)
{
if (empty($this->config['view_path'])) {
$this->config['view_path'] = Container::get('app')->getModulePath() . 'view' . DIRECTORY_SEPARATOR;
}
$request = Container::get('request');
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 . DIRECTORY_SEPARATOR : '');
} else {
$path = isset($module) ? Container::get('app')->getAppPath() . $module . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR : $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('.', DIRECTORY_SEPARATOR, $controller) . $depr . $request->action();
} elseif (false === strpos($template, $depr)) {
$template = str_replace('.', DIRECTORY_SEPARATOR, $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;
}
}
}