first commit

This commit is contained in:
Gnieark 2018-03-17 13:50:04 +01:00
commit 740532a4a7
4 changed files with 128 additions and 0 deletions

1
README.md Normal file
View File

@ -0,0 +1 @@
# tplBlock

86
class.TplBlock.php Normal file
View File

@ -0,0 +1,86 @@
<?php
class InvalidTemplateException extends UnexpectedValueException{
}
class TplBlock {
const blockStartStart = '<!-- BEGIN ';
const blockStartEnd = ' -->';
const blockEndStart = '<!-- END ';
const blockEndEnd = ' -->';
const startEnclosure = '{{';
const endEnclosure = '}}';
public $name = '';
private $vars = array();
private $subBlocs = array();
/*
* Initialise TplBlock
* Input object name
*/
public function __construct(STRING $name =""){
$this->name = $name;
}
/*
* Add simple vars
* Input array structured like:
* {"key":"value","key2":"value2"}
*/
public function add_vars(ARRAY $vars){
$this->vars = array_merge($this->vars,$vars);
}
public function add_sub_block(TplBlock $bloc){
if(empty($bloc->name)){
throw new InvalidTemplateException("A sub tpl bloc can't have an empty name");
return false;
}
$this->subBlocs[$bloc->name][] = $bloc;
}
/*
* Shake template and input vars and returns the text
*/
public function apply_tpl_str($str,$subBlocsPath = ""){
//replace all simple vars
$prefix = (empty($subBlocsPath)? "" : $subBlocsPath.".");
foreach($this->vars as $key=>$value){
$str = str_replace(self::startEnclosure . $prefix . $key . self::endEnclosure,
$value,
$str);
}
//Isolate blocs
foreach($this->subBlocs as $blocName => $blocsArr){
$str = preg_replace_callback(
'/' . self::blockStartStart . preg_quote($blocName) . self::blockStartEnd .
'(.*?)'.
self::blockEndStart . preg_quote($blocName). self::blockEndEnd.
'/is',
function($m) use($blocName,$blocsArr,$prefix) {
$out = "";
foreach($blocsArr as $bloc){
$out.=$bloc->apply_tpl_str( $m[1] , $prefix . $blocName );
}
return $out;
}
,$str
);
}
return $str;
}
public function apply_tpl_file($file){
if(!$tplStr = file_get_contents($file)){
throw new InvalidTemplateException("Cannot read given file ".$file);
return false;
}
return $this->apply_tpl_str($tplStr);
}
}

15
test-TplBlock/sample.txt Normal file
View File

@ -0,0 +1,15 @@
hello {{title}} {{name}} {{firstname}}
The first primes numbers are:
<!-- BEGIN primes -->
- {{primes.number}}
<!-- END primes -->
Lets list all divisors of:
<!-- BEGIN number -->
{{number.value}} Have those divisors:
<!-- BEGIN number.divisor -->
- {{number.divisor.value}}
<!-- END number.divisor -->
<!-- END number -->

26
test-TplBlock/test.php Normal file
View File

@ -0,0 +1,26 @@
<?php
include("../class.TplBlock.php");
$tpl = new TplBlock();
$tpl->add_vars(array(
"name" => "Gnieark",
"title" => "Monsieur",
"firstname" => "Grouik"
)
);
$primes = array(1,2,3,5,7,11);
foreach($primes as $prime){
$tplPrime = new TplBlock('primes');
$tplPrime->add_vars(array('number' => $prime));
$tpl->add_sub_block($tplPrime);
}
echo $tpl->apply_tpl_file("sample.txt");