Skip to content

Instantly share code, notes, and snippets.

@YannDoy
Created February 18, 2017 14:59
Show Gist options
  • Save YannDoy/78a21294ce7e6a9f644431a6bfb1b0c2 to your computer and use it in GitHub Desktop.
Save YannDoy/78a21294ce7e6a9f644431a6bfb1b0c2 to your computer and use it in GitHub Desktop.
<?php
#----------------------------------------------------
# V I E W S
#----------------------------------------------------
/**
* Render a phtml file
*
* @param $_path string the phtml path
* @param $_vars mixed the view vars
* @return string the rendered content
*/
function phtml($_path, $_vars = []) {
ob_start();
$_layout = false;
extract($_vars);
include($_path);
$_content = ob_get_clean();
if ($_layout) {
return render($_layout, $_vars);
}
return $_content;
}
/**
* Render template
*
* @param $path string the phtml path
* @param $vars mixed the view vars
* @return string the rendered content
*/
function render($path, $vars = []) {
$view_path = option('view_path') . $path . '.phtml';
$temp_path = option('temp_path') . 'view_' . md5($path) . '.phtml';
$vars += $GLOBALS[_VERSION]['views'];
if (
! file_exists($temp_path)
|| filemtime($temp_path) < filemtime($view_path)
) {
$content = file_get_contents($view_path);
// parse the view
$content = str_replace(
[
'{{',
'}}',
'{else}',
'{/block}'
],
[
'<?=',
'?>',
'<?php else: ?>',
'<?php }); ?>'
],
$content
);
$content = preg_replace(
[
'#\{layout +(.*?)\}#',
'#\{ *\$([a-zA-Z\_][a-zA-Z0-9\_]*) += +(.*?)}#',
'#\{block +(.*?)}#',
"#\{yield +(.*?)}#",
'#\{/(if|foreach|for|while)\}#',
'#\{(if|elseif|foreach|for|while) +(.*?)\}#'
],
[
"<?php \$_layout = '$1'; ?>",
"<?php set('$1', \$$1 = $2); ?>",
"<?php block('$1', function(\$_vars) { extract(\$_vars); ?>",
"<?= block_yield('$1', \$_vars) ?>",
"<?php end$1; ?>",
"<?php $1($2): ?>"
],
$content
);
file_put_contents($temp_path, $content);
}
return phtml($temp_path, $vars);
}
/**
* Set a view value
*
* @param $name string the view key's name
* @param $value mixed the view key's value
*/
function set($name, $value) {
$GLOBALS[_VERSION]['views'][$name] = $value;
}
/**
* Assign view values
*
* @param array the vars
*/
function assign(array $vars) {
$GLOBALS[_VERSION]['views'] = $vars + $GLOBALS[_VERSION]['views'];
}
/**
* Record block
*
* @param $name string the block name
* @param $block void(array $_vars) the block body
*/
function block($name, $block) {
set("_block_$name", $block);
}
/**
* Yield a block
*
* @param $name string the block name
* @return string the block rendered content
*/
function block_yield($name, $vars = []) {
if (array_key_exists($name = "_block_$name", $GLOBALS[_VERSION]['views'])) {
return call_user_func(
$GLOBALS[_VERSION]['views'][$name],
$vars + $GLOBALS[_VERSION]['views']
);
}
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment