Skip to content

Instantly share code, notes, and snippets.

@mbunge
Created June 24, 2013 13:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbunge/5850006 to your computer and use it in GitHub Desktop.
Read and reander views by recursion
<?php
class View {
public function throwException($message){
throw new Exception($message);
}
public function getPagesBySection($targetSection,$targetFolder,$decoratorCallback=null){
if(!is_dir(dirname($targetFolder))){
$this->throwException(sprintf('Target "%s" is invalid. Type: %s',$targetFolder,gettype($targetFolder)));
}
if(!is_string($targetSection)){
$this->throwException(sprintf('Target "%s" is invalid. Type: %s',$targetFolder,gettype($targetFolder)));
}
$files = scandir($targetFolder); //Ordner "files" auslesen
$result = array();
foreach ($files as $file) { // Ausgabeschleife
if($file != '.' && $file != '..' && $file != '.git' && $file != '.svn'){
$filePath = $targetFolder.$file;
$fileInfo = pathinfo($filePath);
$fileNameParts = explode('_', $fileInfo['filename']);
$section = array_shift($fileNameParts);
if($fileInfo['extension'] == 'php' && $section == $targetSection){
// echo "\n<!-- " . $filePath ." -->\n";
// require_once $filePath;
$result[] = $this->renderViewFile($filePath);
}
}
}
if($decoratorCallback === null || !is_callable($decoratorCallback)){
$decoratorCallback = function($result){
return implode("\n",$result);
};
}
return $decoratorCallback($result);
}
/**
* Export given outputstream to html
*/
public function saveContentToFile($content,$target){
if(!is_dir(dirname($target))){
throw new Exception(sprintf('Target "%s" is invalid. Type: %s',$target,gettype($target)));
}
$result = file_put_contents($target, $content);
return $result > 0;
}
public function renderViewFile($sourceFile,$vars=array()){
if(!is_file($sourceFile)){
throw new Exception(sprintf('Sourcefile "%s" is invalid. Type: %s',$sourceFile,gettype($sourceFile)));
}
//create separate enviroment
$output = function () use($vars,$sourceFile){
ob_start();
extract($vars,EXTR_SKIP);
ob_implicit_flush(false);
require($sourceFile);
return ob_get_clean();
};
return $output();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment