summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLaria Carolin Chabowski <laria@laria.me>2020-04-30 09:38:05 +0200
committerLaria Carolin Chabowski <laria@laria.me>2020-04-30 09:38:25 +0200
commit2381c52c690342f773a7cfa500387b6bfad76952 (patch)
tree340296ea529e40b81012c936703429a86481788e
parent2d26169b367af60cbc03d417c09918f50aa3b882 (diff)
downloadste-2381c52c690342f773a7cfa500387b6bfad76952.tar.gz
ste-2381c52c690342f773a7cfa500387b6bfad76952.tar.bz2
ste-2381c52c690342f773a7cfa500387b6bfad76952.zip
Automatic code formatting
Also add git hooks that checks formatting
-rw-r--r--.gitignore1
-rw-r--r--.php_cs.dist12
-rw-r--r--example/index.php20
-rwxr-xr-xgit-hooks/hooks/pre-commit52
-rwxr-xr-xgit-hooks/install.sh16
-rwxr-xr-xgit-hooks/loader.sh10
-rw-r--r--src/ste/ASTNode.php6
-rw-r--r--src/ste/BreakException.php4
-rw-r--r--src/ste/Calc.php65
-rw-r--r--src/ste/CantLoadTemplate.php4
-rw-r--r--src/ste/CantSaveTemplate.php4
-rw-r--r--src/ste/ContinueException.php4
-rw-r--r--src/ste/FatalRuntimeError.php4
-rw-r--r--src/ste/FilesystemStorageAccess.php26
-rw-r--r--src/ste/Misc.php6
-rw-r--r--src/ste/ParseCompileError.php9
-rw-r--r--src/ste/Parser.php178
-rw-r--r--src/ste/RuntimeError.php4
-rw-r--r--src/ste/STECore.php75
-rw-r--r--src/ste/STEStandardLibrary.php104
-rw-r--r--src/ste/Scope.php76
-rw-r--r--src/ste/StorageAccess.php3
-rw-r--r--src/ste/StorageAccessFailure.php4
-rw-r--r--src/ste/TagNode.php6
-rw-r--r--src/ste/TextNode.php8
-rw-r--r--src/ste/Transcompiler.php200
-rw-r--r--src/ste/VarNotInScope.php4
-rw-r--r--src/ste/VariableNode.php16
-rw-r--r--ste.php62
-rw-r--r--steloader.php5
-rw-r--r--tests/test.php11
-rw-r--r--tests/test_array/code.php3
-rw-r--r--tests/test_blocks/code.php4
-rw-r--r--tests/test_closure/code.php4
-rw-r--r--tests/test_escapes/code.php5
-rw-r--r--tests/test_foreach/code.php3
-rw-r--r--tests/test_getset/code.php3
-rw-r--r--tests/test_loop/code.php4
-rw-r--r--tests/test_mktag/code.php4
-rw-r--r--tests/test_pseudotags/code.php4
-rw-r--r--tests/test_recursive/code.php3
-rw-r--r--tests/test_scoping/code.php4
-rw-r--r--tests/test_short/code.php4
-rw-r--r--tests/test_simple/code.php3
-rw-r--r--tests/test_tagname/code.php8
45 files changed, 663 insertions, 392 deletions
diff --git a/.gitignore b/.gitignore
index 22d0d82..234ce20 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
vendor
+.php_cs.cache
diff --git a/.php_cs.dist b/.php_cs.dist
new file mode 100644
index 0000000..314dfd7
--- /dev/null
+++ b/.php_cs.dist
@@ -0,0 +1,12 @@
+<?php
+$finder = PhpCsFixer\Finder::create()
+ ->notPath('vendor')
+ ->in(__DIR__);
+
+return PhpCsFixer\Config::create()
+ ->setRules([
+ '@PSR1' => true,
+ '@PSR2' => true,
+ ])
+ ->setFinder($finder)
+;
diff --git a/example/index.php b/example/index.php
index bd03a43..4a96410 100644
--- a/example/index.php
+++ b/example/index.php
@@ -14,29 +14,31 @@ $ste = new ste\STECore(
);
# Set STE to a more verbose behavior:
-$ste->mute_runtime_errors = False;
+$ste->mute_runtime_errors = false;
# First, lets define some custom tags.
# <ste:uppercase> will exchange all letters with their uppercase complement
-$ste->register_tag("uppercase",
- function($ste, $params, $sub)
- {
+$ste->register_tag(
+ "uppercase",
+ function ($ste, $params, $sub) {
$text = $sub($ste); # Get the tags content
return strtoupper($text); # Return the new text.
}
);
# <ste:repeat> will repeat its content n times (<ste:for> could be used too, but i needed more examples :-P )
-$ste->register_tag("repeat",
- function($ste, $params, $sub)
- {
+$ste->register_tag(
+ "repeat",
+ function ($ste, $params, $sub) {
$output = "";
- if(!is_numeric($params["n"]))
+ if (!is_numeric($params["n"])) {
throw new ste\RuntimeError("Sorry, but parameter n must be a number...");
+ }
- for($i = 0; $i < $params["n"]; ++$i)
+ for ($i = 0; $i < $params["n"]; ++$i) {
$output .= $sub($ste);
+ }
return $output;
}
diff --git a/git-hooks/hooks/pre-commit b/git-hooks/hooks/pre-commit
new file mode 100755
index 0000000..5666e93
--- /dev/null
+++ b/git-hooks/hooks/pre-commit
@@ -0,0 +1,52 @@
+#!/bin/sh
+
+set -e
+
+gitdir="$(git rev-parse --git-dir)"
+
+changed_files() {
+ git diff --name-status --cached HEAD | tr '\011' '\012' | awk '
+ /^[ADMTUXB]/ { n = 1; next }
+ /^[CR]/ { n = 2; next }
+ n > 0 {
+ print $0
+ n--
+ }
+ '
+}
+
+staged_file_hash() {
+ git ls-files -s "$1" | cut -d' ' -f2
+}
+
+lint_php() {
+ php -l >/dev/null
+}
+
+lint_php_cs_fixer() {
+ php-cs-fixer fix --config="$gitdir/../.php_cs.dist" -v --dry-run --using-cache=no --show-progress=none - >&2
+}
+
+lint_changes() {
+ linter_name="$1"
+ grep_pattern="$2"
+ linter_func="$3"
+
+ failcount="$(changed_files | grep "$grep_pattern" | while read -r f; do
+ hash="$(staged_file_hash "$f")"
+ if [ -n "$hash" ]; then
+ if ! git cat-file blob "$hash" | "$linter_func"; then
+ echo >&2
+ echo "Linter $linter_name reported error for: $f" >&2
+ echo >&2
+
+ echo failed
+ fi
+ fi
+ done | wc -l)"
+
+ [ "$failcount" -eq 0 ] || return 1
+}
+
+lint_changes "php -l" '\.php$' lint_php || exit 1
+lint_changes "php_cs_fixer" '\.php$' lint_php_cs_fixer || exit 1
diff --git a/git-hooks/install.sh b/git-hooks/install.sh
new file mode 100755
index 0000000..17d59bc
--- /dev/null
+++ b/git-hooks/install.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+
+set -e
+
+githooks_dir="$(git rev-parse --git-dir)"
+for hook in hooks/*; do
+ hook="${hook#hooks/}"
+ if [ -f "$githooks_dir/hooks/$hook" ]; then
+ mv "$githooks_dir/hooks/$hook" "$githooks_dir/hooks/own_$hook"
+ fi
+
+ echo '#!/bin/sh
+ exec "$(git rev-parse --git-dir)/../git-hooks/loader.sh" '"$hook"' "$@"
+ ' > "$githooks_dir/hooks/$hook"
+ chmod +x "$githooks_dir/hooks/$hook"
+done
diff --git a/git-hooks/loader.sh b/git-hooks/loader.sh
new file mode 100755
index 0000000..eadafa6
--- /dev/null
+++ b/git-hooks/loader.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+set -e
+
+hook="$1"
+shift
+
+gitdir="$(git rev-parse --git-dir)"
+[ -x "$gitdir/hooks/own_$hook" ] && "$gitdir/hooks/own_$hook" "$@"
+[ -x "$gitdir/../git-hooks/hooks/$hook" ] && "$gitdir/../git-hooks/hooks/$hook" "$@"
diff --git a/src/ste/ASTNode.php b/src/ste/ASTNode.php
index ea40bac..2163161 100644
--- a/src/ste/ASTNode.php
+++ b/src/ste/ASTNode.php
@@ -2,10 +2,12 @@
namespace kch42\ste;
-abstract class ASTNode {
+abstract class ASTNode
+{
public $tpl;
public $offset;
- public function __construct($tpl, $off) {
+ public function __construct($tpl, $off)
+ {
$this->tpl = $tpl;
$this->offset = $off;
}
diff --git a/src/ste/BreakException.php b/src/ste/BreakException.php
index 563bf53..f91cf6a 100644
--- a/src/ste/BreakException.php
+++ b/src/ste/BreakException.php
@@ -2,4 +2,6 @@
namespace kch42\ste;
-class BreakException extends \Exception { }
+class BreakException extends \Exception
+{
+}
diff --git a/src/ste/Calc.php b/src/ste/Calc.php
index e700c4f..64d2b7a 100644
--- a/src/ste/Calc.php
+++ b/src/ste/Calc.php
@@ -3,11 +3,15 @@
namespace kch42\ste;
/* Class Calc contains static methods needed by <ste:calc /> */
-class Calc {
- private function __construct() {}
+class Calc
+{
+ private function __construct()
+ {
+ }
/* We could also just eval() the $infix_math code, but this is much cooler :-D (Parser inception) */
- public static function shunting_yard($infix_math) {
+ public static function shunting_yard($infix_math)
+ {
$operators = array(
"+" => array("l", 2),
"-" => array("l", 2),
@@ -20,16 +24,18 @@ class Calc {
);
preg_match_all("/\s*(?:(?:[+\\-\\*\\/\\^\\(\\)])|(\\d*[\\.]?\\d*))\\s*/s", $infix_math, $tokens, PREG_PATTERN_ORDER);
- $tokens_raw = array_filter(array_map('trim', $tokens[0]), function($x) { return ($x === "0") || (!empty($x)); });
+ $tokens_raw = array_filter(array_map('trim', $tokens[0]), function ($x) {
+ return ($x === "0") || (!empty($x));
+ });
$output_queue = array();
$op_stack = array();
- $lastpriority = NULL;
+ $lastpriority = null;
/* Make - unary, if neccessary */
$tokens = array();
- foreach($tokens_raw as $token) {
+ foreach ($tokens_raw as $token) {
$priority = isset($operators[$token]) ? $operators[$token][1] : -1;
- if(($token == "-") && (($lastpriority === NULL) || ($lastpriority >= 0))) {
+ if (($token == "-") && (($lastpriority === null) || ($lastpriority >= 0))) {
$priority = $operators["_"][1];
$tokens[] = "_";
} else {
@@ -38,35 +44,35 @@ class Calc {
$lastpriority = $priority;
}
- while(!empty($tokens)) {
+ while (!empty($tokens)) {
$token = array_shift($tokens);
- if(is_numeric($token)) {
+ if (is_numeric($token)) {
$output_queue[] = $token;
- } else if($token == "(") {
+ } elseif ($token == "(") {
$op_stack[] = $token;
- } else if($token == ")") {
+ } elseif ($token == ")") {
$lbr_found = false;
- while(!empty($op_stack)) {
+ while (!empty($op_stack)) {
$op = array_pop($op_stack);
- if($op == "(") {
+ if ($op == "(") {
$lbr_found = true;
break;
}
$output_queue[] = $op;
}
- if(!$lbr_found) {
+ if (!$lbr_found) {
throw new RuntimeError("Bracket mismatch.");
}
- } else if(!isset($operators[$token])) {
+ } elseif (!isset($operators[$token])) {
throw new RuntimeError("Invalid token ($token): Not a number, bracket or operator. Stop.");
} else {
$priority = $operators[$token][1];
- if($operators[$token][0] == "l") {
- while((!empty($op_stack)) and ($priority <= $operators[$op_stack[count($op_stack)-1]][1])) {
+ if ($operators[$token][0] == "l") {
+ while ((!empty($op_stack)) and ($priority <= $operators[$op_stack[count($op_stack)-1]][1])) {
$output_queue[] = array_pop($op_stack);
}
} else {
- while((!empty($op_stack)) and ($priority < $operators[$op_stack[count($op_stack)-1]][1])) {
+ while ((!empty($op_stack)) and ($priority < $operators[$op_stack[count($op_stack)-1]][1])) {
$output_queue[] = array_pop($op_stack);
}
}
@@ -74,9 +80,9 @@ class Calc {
}
}
- while(!empty($op_stack)) {
+ while (!empty($op_stack)) {
$op = array_pop($op_stack);
- if($op == "(") {
+ if ($op == "(") {
throw new RuntimeError("Bracket mismatch...");
}
$output_queue[] = $op;
@@ -85,18 +91,20 @@ class Calc {
return $output_queue;
}
- public static function pop2(&$array) {
+ public static function pop2(&$array)
+ {
$rv = array(array_pop($array), array_pop($array));
- if(array_search(NULL, $rv, true) !== false) {
+ if (array_search(null, $rv, true) !== false) {
throw new RuntimeError("Not enough numbers on stack. Invalid formula.");
}
return $rv;
}
- public static function calc_rpn($rpn) {
+ public static function calc_rpn($rpn)
+ {
$stack = array();
- foreach($rpn as $token) {
- switch($token) {
+ foreach ($rpn as $token) {
+ switch ($token) {
case "+":
list($b, $a) = self::pop2($stack);
$stack[] = $a + $b;
@@ -119,7 +127,7 @@ class Calc {
break;
case "_":
$a = array_pop($stack);
- if($a === NULL) {
+ if ($a === null) {
throw new RuntimeError("Not enough numbers on stack. Invalid formula.");
}
$stack[] = -$a;
@@ -132,7 +140,8 @@ class Calc {
return array_pop($stack);
}
- public static function calc($expr) {
+ public static function calc($expr)
+ {
return self::calc_rpn(self::shunting_yard($expr));
}
-} \ No newline at end of file
+}
diff --git a/src/ste/CantLoadTemplate.php b/src/ste/CantLoadTemplate.php
index 82c7a9f..20200d6 100644
--- a/src/ste/CantLoadTemplate.php
+++ b/src/ste/CantLoadTemplate.php
@@ -9,4 +9,6 @@ namespace kch42\ste;
* Class: CantLoadTemplate
* An exception that a <StorageAccess> implementation can throw, if it is unable to load a template.
*/
-class CantLoadTemplate extends StorageAccessFailure { }
+class CantLoadTemplate extends StorageAccessFailure
+{
+}
diff --git a/src/ste/CantSaveTemplate.php b/src/ste/CantSaveTemplate.php
index 1072ad1..edbb93e 100644
--- a/src/ste/CantSaveTemplate.php
+++ b/src/ste/CantSaveTemplate.php
@@ -9,4 +9,6 @@ namespace kch42\ste;
* Class: CantSaveTemplate
* An exception that a <StorageAccess> implementation can throw, if it is unable to save a template.
*/
-class CantSaveTemplate extends StorageAccessFailure { }
+class CantSaveTemplate extends StorageAccessFailure
+{
+}
diff --git a/src/ste/ContinueException.php b/src/ste/ContinueException.php
index af79b1b..784166e 100644
--- a/src/ste/ContinueException.php
+++ b/src/ste/ContinueException.php
@@ -2,4 +2,6 @@
namespace kch42\ste;
-class ContinueException extends \Exception { }
+class ContinueException extends \Exception
+{
+}
diff --git a/src/ste/FatalRuntimeError.php b/src/ste/FatalRuntimeError.php
index d5ca735..ab40af5 100644
--- a/src/ste/FatalRuntimeError.php
+++ b/src/ste/FatalRuntimeError.php
@@ -10,4 +10,6 @@ namespace kch42\ste;
* An Exception a tag can throw, if a fatal (irreparable) runtime error occurred.
* This Exception will always "bubble up" so you probably want to catch them. Remember that this exception is also in the namespace ste!
*/
-class FatalRuntimeError extends \Exception {}
+class FatalRuntimeError extends \Exception
+{
+}
diff --git a/src/ste/FilesystemStorageAccess.php b/src/ste/FilesystemStorageAccess.php
index d2e5e7f..0bae3b2 100644
--- a/src/ste/FilesystemStorageAccess.php
+++ b/src/ste/FilesystemStorageAccess.php
@@ -9,7 +9,8 @@ namespace kch42\ste;
* Class: FilesystemStorageAccess
* The default <StorageAccess> implementation for loading / saving templates into a directory structure.
*/
-class FilesystemStorageAccess implements StorageAccess {
+class FilesystemStorageAccess implements StorageAccess
+{
protected $sourcedir;
protected $transcompileddir;
@@ -20,18 +21,20 @@ class FilesystemStorageAccess implements StorageAccess {
* $src - The directory with the sources (Writing permissions are not mandatory, because STE does not save template sources).
* $transc - The directory with the transcompiled templates (the PHP instance / the HTTP Server needs writing permissions to this directory).
*/
- public function __construct($src, $transc) {
+ public function __construct($src, $transc)
+ {
$this->sourcedir = $src;
$this->transcompileddir = $transc;
}
- public function load($tpl, &$mode) {
+ public function load($tpl, &$mode)
+ {
$src_fn = $this->sourcedir . "/" . $tpl;
$transc_fn = $this->transcompileddir . "/" . $tpl . ".php";
- if($mode == StorageAccess::MODE_SOURCE) {
+ if ($mode == StorageAccess::MODE_SOURCE) {
$content = @file_get_contents($src_fn);
- if($content === false) {
+ if ($content === false) {
throw new CantLoadTemplate("Template not found.");
}
return $content;
@@ -40,16 +43,16 @@ class FilesystemStorageAccess implements StorageAccess {
$src_stat = @stat($src_fn);
$transc_stat = @stat($transc_fn);
- if(($src_stat === false) and ($transc_stat === false)) {
+ if (($src_stat === false) and ($transc_stat === false)) {
throw new CantLoadTemplate("Template not found.");
- } else if($transc_stat === false) {
+ } elseif ($transc_stat === false) {
$mode = StorageAccess::MODE_SOURCE;
return file_get_contents($src_fn);
- } else if($src_stat === false) {
+ } elseif ($src_stat === false) {
include($transc_fn);
return $transcompile_fx;
} else {
- if($src_stat["mtime"] > $transc_stat["mtime"]) {
+ if ($src_stat["mtime"] > $transc_stat["mtime"]) {
$mode = StorageAccess::MODE_SOURCE;
return file_get_contents($src_fn);
} else {
@@ -59,10 +62,11 @@ class FilesystemStorageAccess implements StorageAccess {
}
}
- public function save($tpl, $data, $mode) {
+ public function save($tpl, $data, $mode)
+ {
$fn = (($mode == StorageAccess::MODE_SOURCE) ? $this->sourcedir : $this->transcompileddir) . "/" . $tpl . (($mode == StorageAccess::MODE_TRANSCOMPILED) ? ".php" : "");
@mkdir(dirname($fn), 0777, true);
- if(file_put_contents($fn, "<?php\n\$transcompile_fx = $data; ?>") === false) {
+ if (file_put_contents($fn, "<?php\n\$transcompile_fx = $data; ?>") === false) {
throw new CantSaveTemplate("Unable to save template.");
}
}
diff --git a/src/ste/Misc.php b/src/ste/Misc.php
index 39ad30c..d017ee3 100644
--- a/src/ste/Misc.php
+++ b/src/ste/Misc.php
@@ -2,8 +2,10 @@
namespace kch42\ste;
-class Misc {
- public static function escape_text($text) {
+class Misc
+{
+ public static function escape_text($text)
+ {
return addcslashes($text, "\r\n\t\$\0..\x1f\\\"\x7f..\xff");
}
}
diff --git a/src/ste/ParseCompileError.php b/src/ste/ParseCompileError.php
index 33fd612..f5f0272 100644
--- a/src/ste/ParseCompileError.php
+++ b/src/ste/ParseCompileError.php
@@ -2,19 +2,22 @@
namespace kch42\ste;
-class ParseCompileError extends \Exception {
+class ParseCompileError extends \Exception
+{
public $msg;
public $tpl;
public $off;
- public function __construct($msg, $tpl, $offset, $code = 0, $previous = NULL) {
+ public function __construct($msg, $tpl, $offset, $code = 0, $previous = null)
+ {
$this->msg = $msg;
$this->tpl = $tpl;
$this->off = $offset;
$this->message = "$msg (Template $tpl, Offset $offset)";
}
- public function rewrite($code) {
+ public function rewrite($code)
+ {
$line = substr_count(str_replace("\r\n", "\n", substr($code, 0, $this->off)), "\n") + 1;
$this->message = "{$this->msg} (Template {$this->tpl}, Line $line)";
$this->is_rewritten = true;
diff --git a/src/ste/Parser.php b/src/ste/Parser.php
index 7226c60..40f5f20 100644
--- a/src/ste/Parser.php
+++ b/src/ste/Parser.php
@@ -10,7 +10,8 @@ namespace kch42\ste;
* The class, where the parser lives in. Can not be constructed manually.
* Use the static method parse.
*/
-class Parser {
+class Parser
+{
private $text;
private $name;
private $off;
@@ -21,15 +22,17 @@ class Parser {
const ESCAPES_DEFAULT = '$?~{}|\\';
- private function __construct($text, $name) {
+ private function __construct($text, $name)
+ {
$this->text = $text;
$this->name = $name;
$this->off = 0;
$this->len = mb_strlen($text);
}
- private function next($n = 1) {
- if($n <= 0) {
+ private function next($n = 1)
+ {
+ if ($n <= 0) {
throw new \InvalidArgumentException("\$n must be > 0");
}
$c = mb_substr($this->text, $this->off, $n);
@@ -37,48 +40,53 @@ class Parser {
return $c;
}
- private function eof() {
+ private function eof()
+ {
return ($this->off == $this->len);
}
- private function back($n = 1) {
- if($n <= 0) {
+ private function back($n = 1)
+ {
+ if ($n <= 0) {
throw new \InvalidArgumentException("\$n must be > 0");
}
$this->off = max($this->off - $n, 0);
}
- private function search_off($needle) {
+ private function search_off($needle)
+ {
return mb_strpos($this->text, $needle, $this->off);
}
- private function search_multi($needles) {
+ private function search_multi($needles)
+ {
$oldoff = $this->off;
$minoff = $this->len;
- $which = NULL;
+ $which = null;
- foreach($needles as $key => $needle) {
- if(($off = $this->search_off($needle)) === false) {
+ foreach ($needles as $key => $needle) {
+ if (($off = $this->search_off($needle)) === false) {
continue;
}
- if($off < $minoff) {
+ if ($off < $minoff) {
$minoff = $off;
$which = $key;
}
}
- $this->off = $minoff + (($which === NULL) ? 0 : mb_strlen((string) $needles[$which]));
+ $this->off = $minoff + (($which === null) ? 0 : mb_strlen((string) $needles[$which]));
return array($which, $minoff, mb_substr($this->text, $oldoff, $minoff - $oldoff), $oldoff);
}
- private function search($needle) {
+ private function search($needle)
+ {
$oldoff = $this->off;
$off = $this->search_off($needle);
- if($off === false) {
+ if ($off === false) {
$this->off = $this->len;
return array(false, mb_substr($this->text, $oldoff), $oldoff);
}
@@ -87,10 +95,11 @@ class Parser {
return array($off, mb_substr($this->text, $oldoff, $off - $oldoff), $oldoff);
}
- private function take_while($cb) {
+ private function take_while($cb)
+ {
$s = "";
- while(($c = $this->next()) !== "") {
- if(!call_user_func($cb, $c)) {
+ while (($c = $this->next()) !== "") {
+ if (!call_user_func($cb, $c)) {
$this->back();
return $s;
}
@@ -99,14 +108,18 @@ class Parser {
return $s;
}
- private function skip_ws() {
+ private function skip_ws()
+ {
$this->take_while("ctype_space");
}
- private function get_name() {
+ private function get_name()
+ {
$off = $this->off;
- $name = $this->take_while(function($c) { return ctype_alnum($c) || ($c == "_"); });
- if(mb_strlen($name) == 0) {
+ $name = $this->take_while(function ($c) {
+ return ctype_alnum($c) || ($c == "_");
+ });
+ if (mb_strlen($name) == 0) {
throw new ParseCompileError("Expected a name (alphanumeric chars + '_', at least one char)", $this->name, $off);
}
return $name;
@@ -128,7 +141,8 @@ class Parser {
* Throws:
* <ParseCompileError>
*/
- public static function parse($text, $name) {
+ public static function parse($text, $name)
+ {
$obj = new self($text, $name);
$res = $obj->parse_text(
self::ESCAPES_DEFAULT, /* Escapes */
@@ -137,39 +151,40 @@ class Parser {
return self::tidyup_ast($res[0]);
}
- private static function tidyup_ast($ast) {
+ private static function tidyup_ast($ast)
+ {
$out = array();
- $prevtext = NULL;
+ $prevtext = null;
$first = true;
- foreach($ast as $node) {
- if($node instanceof TextNode) {
- if($prevtext === NULL) {
+ foreach ($ast as $node) {
+ if ($node instanceof TextNode) {
+ if ($prevtext === null) {
$prevtext = $node;
} else {
$prevtext->text .= $node->text;
}
} else {
- if($prevtext !== NULL) {
- if($first) {
+ if ($prevtext !== null) {
+ if ($first) {
$prevtext->text = ltrim($prevtext->text);
}
- if($prevtext->text != "") {
+ if ($prevtext->text != "") {
$out[] = $prevtext;
}
}
- $prevtext = NULL;
+ $prevtext = null;
$first = false;
- if($node instanceof TagNode) {
+ if ($node instanceof TagNode) {
$node->sub = self::tidyup_ast($node->sub);
- foreach($node->params as $k => &$v) {
+ foreach ($node->params as $k => &$v) {
$v = self::tidyup_ast($v);
}
unset($v);
} else { /* VariableNode */
- foreach($node->arrayfields as &$v) {
+ foreach ($node->arrayfields as &$v) {
$v = self::tidyup_ast($v);
}
unset($v);
@@ -179,11 +194,11 @@ class Parser {
}
}
- if($prevtext !== NULL) {
- if($first) {
+ if ($prevtext !== null) {
+ if ($first) {
$prevtext->text = ltrim($prevtext->text);
}
- if($prevtext->text != "") {
+ if ($prevtext->text != "") {
$out[] = $prevtext;
}
}
@@ -191,7 +206,8 @@ class Parser {
return $out;
}
- private function parse_text($escapes, $flags, $breakon = NULL, $separator = NULL, $nullaction = NULL, $opentag = NULL, $openedat = -1) {
+ private function parse_text($escapes, $flags, $breakon = null, $separator = null, $nullaction = null, $opentag = null, $openedat = -1)
+ {
$elems = array();
$astlist = array();
@@ -203,30 +219,30 @@ class Parser {
"var" => '$',
);
- if($flags & self::PARSE_TAG) {
+ if ($flags & self::PARSE_TAG) {
$needles["tagopen"] = '<ste:';
$needles["closetagopen"] = '</ste:';
}
- if($flags & self::PARSE_SHORT) {
+ if ($flags & self::PARSE_SHORT) {
$needles["shortifopen"] = '?{';
$needles["shortcompopen"] = '~{';
}
- if($separator !== NULL) {
+ if ($separator !== null) {
$needles["sep"] = $separator;
}
- if($breakon !== NULL) {
+ if ($breakon !== null) {
$needles["break"] = $breakon;
}
- for(;;) {
+ for (;;) {
list($which, $off, $before, $offbefore) = $this->search_multi($needles);
$astlist[] = new TextNode($this->name, $offbefore, $before);
- switch($which) {
- case NULL:
- if($nullaction === NULL) {
+ switch ($which) {
+ case null:
+ if ($nullaction === null) {
$elems[] = $astlist;
return $elems;
} else {
@@ -235,14 +251,14 @@ class Parser {
break;
case "commentopen":
list($off, $before, $offbefore) = $this->search("</ste:comment>");
- if($off === false) {
+ if ($off === false) {
throw new ParseCompileError("ste:comment was not closed", $this->name, $offbefore);
}
break;
case "rawopen":
$off_start = $off;
list($off, $before, $offbefore) = $this->search("</ste:rawtext>");
- if($off === false) {
+ if ($off === false) {
throw new ParseCompileError("ste:rawtext was not closed", $this->name, $off_start);
}
$astlist[] = new TextNode($this->name, $off_start, $before);
@@ -255,14 +271,14 @@ class Parser {
$name = $this->get_name();
$this->skip_ws();
$off = $this->off;
- if($this->next() != ">") {
+ if ($this->next() != ">") {
throw new ParseCompileError("Expected '>' in closing ste-Tag", $this->name, $off);
}
- if($opentag === NULL) {
+ if ($opentag === null) {
throw new ParseCompileError("Found closing ste:$name tag, but no tag was opened", $this->name, $off_start);
}
- if($opentag != $name) {
+ if ($opentag != $name) {
throw new ParseCompileError("Open ste:$opentag was not closed", $this->name, $openedat);
}
@@ -270,7 +286,7 @@ class Parser {
return $elems;
case "escape":
$c = $this->next();
- if(mb_strpos($escapes, $c) !== false) {
+ if (mb_strpos($escapes, $c) !== false) {
$astlist[] = new TextNode($this->name, $off, $c);
} else {
$astlist[] = new TextNode($this->name, $off, '\\');
@@ -279,7 +295,7 @@ class Parser {
break;
case "shortifopen":
$shortelems = $this->parse_short("?{", $off);
- if(count($shortelems) != 3) {
+ if (count($shortelems) != 3) {
throw new ParseCompileError("A short if tag must have the form ?{..|..|..}", $this->name, $off);
}
@@ -302,7 +318,7 @@ class Parser {
break;
case "shortcompopen":
$shortelems = $this->parse_short("~{", $off);
- if(count($shortelems) != 3) {
+ if (count($shortelems) != 3) {
throw new ParseCompileError("A short comparasion tag must have the form ~{..|..|..}", $this->name, $off);
}
@@ -336,7 +352,8 @@ class Parser {
return $elems;
}
- private function parse_short($shortname, $openedat) {
+ private function parse_short($shortname, $openedat)
+ {
$tplname = $this->name;
return $this->parse_text(
@@ -344,43 +361,45 @@ class Parser {
self::PARSE_SHORT | self::PARSE_TAG, /* Flags */
'}', /* Break on */
'|', /* Separator */
- function() use ($shortname, $tplname, $openedat) { /* NULL action */
+ function () use ($shortname, $tplname, $openedat) { /* NULL action */
throw new ParseCompileError("Unclosed $shortname", $tplname, $openedat);
},
- NULL, /* Open tag */
+ null, /* Open tag */
$openedat /* Opened at */
);
}
- private function parse_var($openedat, $curly) {
+ private function parse_var($openedat, $curly)
+ {
$varnode = new VariableNode($this->name, $openedat);
$varnode->name = $this->get_name();
- if(!$this->eof()) {
+ if (!$this->eof()) {
$varnode->arrayfields = $this->parse_array();
}
- if(($curly) && ($this->next() != "}")) {
+ if (($curly) && ($this->next() != "}")) {
throw new ParseCompileError("Unclosed '\${'", $this->name, $openedat);
}
return $varnode;
}
- private function parse_array() {
+ private function parse_array()
+ {
$tplname = $this->name;
$arrayfields = array();
- while($this->next() == "[") {
+ while ($this->next() == "[") {
$openedat = $this->off - 1;
$res = $this->parse_text(
self::ESCAPES_DEFAULT, /* Escapes */
0, /* Flags */
']', /* Break on */
- NULL, /* Separator */
- function() use ($tplname, $openedat) { /* NULL action */
+ null, /* Separator */
+ function () use ($tplname, $openedat) { /* NULL action */
throw new ParseCompileError("Unclosed array access '[...]'", $tplname, $openedat);
},
- NULL, /* Open tag */
+ null, /* Open tag */
$openedat /* Opened at */
);
$arrayfields[] = $res[0];
@@ -390,7 +409,8 @@ class Parser {
return $arrayfields;
}
- private function parse_tag($openedat) {
+ private function parse_tag($openedat)
+ {
$tplname = $this->name;
$this->skip_ws();
@@ -399,13 +419,13 @@ class Parser {
$tag->params = array();
$tag->sub = array();
- for(;;) {
+ for (;;) {
$this->skip_ws();
- switch($this->next()) {
+ switch ($this->next()) {
case '/': /* Self-closing tag */
$this->skip_ws();
- if($this->next() != '>') {
+ if ($this->next() != '>') {
throw new ParseCompileError("Unclosed opening <ste: tag (expected >)", $this->name, $openedat);
}
@@ -414,9 +434,9 @@ class Parser {
$sub = $this->parse_text(
self::ESCAPES_DEFAULT, /* Escapes */
self::PARSE_SHORT | self::PARSE_TAG, /* Flags */
- NULL, /* Break on */
- NULL, /* Separator */
- function() use ($name, $tplname, $openedat) { /* NULL action */
+ null, /* Break on */
+ null, /* Separator */
+ function () use ($name, $tplname, $openedat) { /* NULL action */
throw new ParseCompileError("Open ste:$name tag was not closed", $tplname, $openedat);
},
$tag->name, /* Open tag */
@@ -430,13 +450,13 @@ class Parser {
$param = $this->get_name();
$this->skip_ws();
- if($this->next() != '=') {
+ if ($this->next() != '=') {
throw new ParseCompileError("Expected '=' after tag parameter name", $this->name, $this->off - 1);
}
$this->skip_ws();
$quot = $this->next();
- if(($quot != '"') && ($quot != "'")) {
+ if (($quot != '"') && ($quot != "'")) {
throw new ParseCompileError("Expected ' or \" after '=' of tag parameter", $this->name, $this->off - 1);
}
@@ -445,11 +465,11 @@ class Parser {
self::ESCAPES_DEFAULT . $quot, /* Escapes */
0, /* Flags */
$quot, /* Break on */
- NULL, /* Separator */
- function() use ($quot, $tplname, $off) { /* NULL action */
+ null, /* Separator */
+ function () use ($quot, $tplname, $off) { /* NULL action */
throw new ParseCompileError("Open tag parameter value ($quot) was not closed", $tplname, $off);
},
- NULL, /* Open tag */
+ null, /* Open tag */
$off /* Opened at */
);
$tag->params[$param] = $paramval[0];
diff --git a/src/ste/RuntimeError.php b/src/ste/RuntimeError.php
index ff3b26d..dace1d4 100644
--- a/src/ste/RuntimeError.php
+++ b/src/ste/RuntimeError.php
@@ -10,4 +10,6 @@ namespace kch42\ste;
* An Exception that a tag can throw, if a non-fatal runtime error occurred.
* By default this will return in no output at all. But if <STECore::$mute_runtime_errors> is false, this will generate a error message instead of the tag's output.
*/
-class RuntimeError extends \Exception {}
+class RuntimeError extends \Exception
+{
+}
diff --git a/src/ste/STECore.php b/src/ste/STECore.php
index 297263a..ccb2a22 100644
--- a/src/ste/STECore.php
+++ b/src/ste/STECore.php
@@ -9,7 +9,8 @@ namespace kch42\ste;
* Class: STECore
* The Core of STE
*/
-class STECore {
+class STECore
+{
private $tags;
private $storage_access;
private $cur_tpl_dir;
@@ -36,7 +37,8 @@ class STECore {
* Parameters:
* $storage_access - An Instance of a <StorageAccess> implementation.
*/
- public function __construct($storage_access) {
+ public function __construct($storage_access)
+ {
$this->storage_access = $storage_access;
$this->cur_tpl_dir = "/";
STEStandardLibrary::_register_lib($this);
@@ -59,11 +61,12 @@ class STECore {
* Throws:
* An Exception if the tag could not be registered (if $callback is not callable or if $name is empty)
*/
- public function register_tag($name, $callback) {
- if(!is_callable($callback)) {
+ public function register_tag($name, $callback)
+ {
+ if (!is_callable($callback)) {
throw new \Exception("Can not register tag \"$name\", not callable.");
}
- if(empty($name)) {
+ if (empty($name)) {
throw new \Exception("Can not register tag, empty name.");
}
$this->tags[$name] = $callback;
@@ -84,24 +87,26 @@ class STECore {
* Returns:
* The output of the tag or, if a <RuntimeError> was thrown, the appropiate result (see <$mute_runtime_errors>).
*/
- public function call_tag($name, $params, $sub) {
+ public function call_tag($name, $params, $sub)
+ {
try {
- if(!isset($this->tags[$name])) {
- if($this->fatal_error_on_missing_tag) {
+ if (!isset($this->tags[$name])) {
+ if ($this->fatal_error_on_missing_tag) {
throw new FatalRuntimeError("Can not call tag \"$name\": Does not exist.");
} else {
throw new RuntimeError("Can not call tag \"$name\": Does not exist.");
}
}
return call_user_func($this->tags[$name], $this, $params, $sub);
- } catch(RuntimeError $e) {
- if(!$this->mute_runtime_errors) {
+ } catch (RuntimeError $e) {
+ if (!$this->mute_runtime_errors) {
return "RuntimeError occurred on tag '$name': " . $e->getMessage();
}
}
}
- public function calc($expression) {
+ public function calc($expression)
+ {
return Calc::calc($expression);
}
@@ -121,11 +126,12 @@ class STECore {
* Returns:
* The output of the template.
*/
- public function exectemplate($tpl) {
+ public function exectemplate($tpl)
+ {
$output = "";
$lastblock = $this->load($tpl);
- foreach($this->blockorder as $blockname) {
+ foreach ($this->blockorder as $blockname) {
$output .= $this->blocks[$blockname];
}
@@ -147,7 +153,8 @@ class STECore {
* Returns:
* A Reference to the variable.
*/
- public function &get_var_reference($name, $create_if_not_exist) {
+ public function &get_var_reference($name, $create_if_not_exist)
+ {
$ref = &$this->scope->get_var_reference($name, $create_if_not_exist);
return $ref;
}
@@ -164,7 +171,8 @@ class STECore {
* Throws:
* <RuntimeError> if the variable name can not be parsed (e.g. unbalanced brackets).
*/
- public function set_var_by_name($name, $val) {
+ public function set_var_by_name($name, $val)
+ {
$this->scope->set_var_by_name($name, $val);
}
@@ -179,7 +187,8 @@ class STECore {
* Throws:
* <RuntimeError> if the variable name can not be parsed (e.g. unbalanced brackets).
*/
- public function set_local_var($name, $val) {
+ public function set_local_var($name, $val)
+ {
$this->scope->set_local_var($name, $val);
}
@@ -197,7 +206,8 @@ class STECore {
* Returns:
* The variables value.
*/
- public function get_var_by_name($name) {
+ public function get_var_by_name($name)
+ {
return $this->scope->get_var_by_name($name);
}
@@ -218,18 +228,21 @@ class STECore {
* Returns:
* The result of the template (if $quiet == false).
*/
- public function load($tpl, $quiet = false) {
+ public function load($tpl, $quiet = false)
+ {
$tpldir_b4 = $this->cur_tpl_dir;
/* Resolve ".", ".." and protect from possible LFI */
$tpl = str_replace("\\", "/", $tpl);
- if($tpl[0] != "/") {
+ if ($tpl[0] != "/") {
$tpl = $this->cur_tpl_dir . "/" . $tpl;
}
- $pathex = array_filter(explode("/", $tpl), function($s) { return ($s != ".") and (!empty($s)); });
+ $pathex = array_filter(explode("/", $tpl), function ($s) {
+ return ($s != ".") and (!empty($s));
+ });
$pathex = array_merge($pathex);
- while(($i = array_search("..", $pathex)) !== false) {
- if($i == 0) {
+ while (($i = array_search("..", $pathex)) !== false) {
+ if ($i == 0) {
$pathex = array_slice($pathex, 1);
} else {
$pathex = array_merge(array_slice($pathex, 0, $i), array_slice($pathex, $i + 2));
@@ -238,18 +251,18 @@ class STECore {
$tpl = implode("/", $pathex);
$this->cur_tpl_dir = dirname($tpl);
- if($quiet) {
+ if ($quiet) {
$blocks_back = clone $this->blocks;
$blockorder_back = clone $this->blockorder;
}
$mode = StorageAccess::MODE_TRANSCOMPILED;
$content = $this->storage_access->load($tpl, $mode);
- if($mode == StorageAccess::MODE_SOURCE) {
+ if ($mode == StorageAccess::MODE_SOURCE) {
try {
$ast = Parser::parse($content, $tpl);
$transc = Transcompiler::transcompile($ast);
- } catch(ParseCompileError $e) {
+ } catch (ParseCompileError $e) {
$e->rewrite($content);
throw $e;
}
@@ -261,7 +274,7 @@ class STECore {
$this->cur_tpl_dir = $tpldir_b4;
- if($quiet) {
+ if ($quiet) {
$this->blocks = $blocks_back;
$this->blockorder = $blockorder_back;
} else {
@@ -279,13 +292,15 @@ class STECore {
* Returns:
* true/false.
*/
- public function evalbool($txt) {
+ public function evalbool($txt)
+ {
return trim(@(string)$txt) != "";
}
- public function make_closure($fx) {
+ public function make_closure($fx)
+ {
$bound_scope = $this->scope;
- return function() use($bound_scope, $fx) {
+ return function () use ($bound_scope, $fx) {
$args = func_get_args();
$ste = $args[0];
@@ -297,7 +312,7 @@ class STECore {
$result = call_user_func_array($fx, $args);
$ste->scope = $prev;
return $result;
- } catch(\Exception $e) {
+ } catch (\Exception $e) {
$ste->scope = $prev;
throw $e;
}
diff --git a/src/ste/STEStandardLibrary.php b/src/ste/STEStandardLibrary.php
index 17532a3..9850afe 100644
--- a/src/ste/STEStandardLibrary.php
+++ b/src/ste/STEStandardLibrary.php
@@ -2,145 +2,165 @@
namespace kch42\ste;
-class STEStandardLibrary {
- static public function _register_lib($ste) {
- foreach(get_class_methods(__CLASS__) as $method) {
- if($method[0] != "_") {
+class STEStandardLibrary
+{
+ public static function _register_lib($ste)
+ {
+ foreach (get_class_methods(__CLASS__) as $method) {
+ if ($method[0] != "_") {
$ste->register_tag($method, array(__CLASS__, $method));
}
}
}
- static public function escape($ste, $params, $sub) {
- if($ste->evalbool(@$params["lines"])) {
+ public static function escape($ste, $params, $sub)
+ {
+ if ($ste->evalbool(@$params["lines"])) {
return nl2br(htmlspecialchars(str_replace("\r\n", "\n", $sub($ste))));
} else {
return htmlspecialchars($sub($ste));
}
}
- static public function strlen($ste, $params, $sub) {
+ public static function strlen($ste, $params, $sub)
+ {
return strlen($sub($ste));
}
- static public function arraylen($ste, $params, $sub) {
- if(empty($params["array"])) {
+ public static function arraylen($ste, $params, $sub)
+ {
+ if (empty($params["array"])) {
throw new RuntimeError("Missing array parameter in <ste:arraylen>.");
}
$a = $ste->get_var_by_name($params["array"], false);
return (is_array($a)) ? count($a) : "";
}
- static public function inc($ste, $params, $sub) {
- if(empty($params["var"])) {
+ public static function inc($ste, $params, $sub)
+ {
+ if (empty($params["var"])) {
throw new RuntimeError("Missing var parameter in <ste:inc>.");
}
$ref = &$ste->get_var_reference($params["var"], true);
$ref++;
}
- static public function dec($ste, $params, $sub) {
- if(empty($params["var"])) {
+ public static function dec($ste, $params, $sub)
+ {
+ if (empty($params["var"])) {
throw new RuntimeError("Missing var parameter in <ste:dec>.");
}
$ref = &$ste->get_var_reference($params["var"], true);
$ref--;
}
- static public function date($ste, $params, $sub) {
+ public static function date($ste, $params, $sub)
+ {
return @strftime($sub($ste), empty($params["timestamp"]) ? @time() : (int) $params["timestamp"]);
}
- static public function in_array($ste, $params, $sub) {
- if(empty($params["array"])) {
+ public static function in_array($ste, $params, $sub)
+ {
+ if (empty($params["array"])) {
throw new RuntimeError("Missing array parameter in <ste:in_array>.");
}
$ar = &$ste->get_var_reference($params["array"], false);
- if(!is_array($ar)) {
+ if (!is_array($ar)) {
return "";
}
return in_array($sub($ste), $ar) ? "y" : "";
}
- static public function join($ste, $params, $sub) {
- if(empty($params["array"])) {
+ public static function join($ste, $params, $sub)
+ {
+ if (empty($params["array"])) {
throw new RuntimeError("Missing array parameter in <ste:join>.");
}
return implode($sub($ste), $ste->get_var_by_name($params["array"]));
}
- static public function split($ste, $params, $sub) {
- if(empty($params["array"])) {
+ public static function split($ste, $params, $sub)
+ {
+ if (empty($params["array"])) {
throw new RuntimeError("Missing array parameter in <ste:split>.");
}
- if(empty($params["delim"])) {
+ if (empty($params["delim"])) {
throw new RuntimeError("Missing delim parameter in <ste:split>.");
}
$ste->set_var_by_name($params["array"], explode($params["delim"], $sub($ste)));
}
- static public function array_add($ste, $params, $sub) {
- if(empty($params["array"])) {
+ public static function array_add($ste, $params, $sub)
+ {
+ if (empty($params["array"])) {
throw new RuntimeError("Missing array parameter in <ste:array_add>.");
}
$ar = &$ste->get_var_reference($params["array"], true);
- if(empty($params["key"])) {
+ if (empty($params["key"])) {
$ar[] = $sub($ste);
} else {
$ar[$params["key"]] = $sub($ste);
}
}
- static public function array_filter($ste, $params, $sub)
+ public static function array_filter($ste, $params, $sub)
{
- if(empty($params["array"])) {
+ if (empty($params["array"])) {
throw new RuntimeError("Missing array parameter in <ste:array_filter>.");
}
$ar = $ste->get_var_by_name($params["array"]);
- if(!is_array($ar)) {
+ if (!is_array($ar)) {
throw new RuntimeError("Variable at 'array' is not an array.");
}
$keys = array_keys($ar);
- if(!empty($params["keep_by_keys"])) {
+ if (!empty($params["keep_by_keys"])) {
$keep_by_keys = &$ste->get_var_reference($params["keep_by_keys"], false);
- if(!is_array($keep_by_keys)) {
+ if (!is_array($keep_by_keys)) {
throw new RuntimeError("Variable at 'keep_by_keys' is not an array.");
}
- $delkeys = array_filter($keys, function($k) use ($keep_by_keys) { return !in_array($k, $keep_by_keys); });
- foreach($delkeys as $dk) {
+ $delkeys = array_filter($keys, function ($k) use ($keep_by_keys) {
+ return !in_array($k, $keep_by_keys);
+ });
+ foreach ($delkeys as $dk) {
unset($ar[$dk]);
}
$keys = array_keys($ar);
}
- if(!empty($params["keep_by_values"])) {
+ if (!empty($params["keep_by_values"])) {
$keep_by_values = &$ste->get_var_reference($params["keep_by_values"], false);
- if(!is_array($keep_by_values)) {
+ if (!is_array($keep_by_values)) {
throw new RuntimeError("Variable at 'keep_by_values' is not an array.");
}
- $ar = array_filter($ar, function($v) use ($keep_by_values) { return in_array($v, $keep_by_values); });
+ $ar = array_filter($ar, function ($v) use ($keep_by_values) {
+ return in_array($v, $keep_by_values);
+ });
$keys = array_keys($ar);
}
- if(!empty($params["delete_by_keys"])) {
+ if (!empty($params["delete_by_keys"])) {
$delete_by_keys = &$ste->get_var_reference($params["delete_by_keys"], false);
- if(!is_array($delete_by_keys)) {
+ if (!is_array($delete_by_keys)) {
throw new RuntimeError("Variable at 'delete_by_keys' is not an array.");
}
- $delkeys = array_filter($keys, function($k) use ($delete_by_keys) { return in_array($k, $delete_by_keys); });
- foreach($delkeys as $dk) {
+ $delkeys = array_filter($keys, function ($k) use ($delete_by_keys) {
+ return in_array($k, $delete_by_keys);
+ });
+ foreach ($delkeys as $dk) {
unset($ar[$dk]);
}
$keys = array_keys($ar);
}
- if(!empty($params["delete_by_values"])) {
+ if (!empty($params["delete_by_values"])) {
$delete_by_values = &$ste->get_var_reference($params["delete_by_values"], false);
- if(!is_array($delete_by_values)) {
+ if (!is_array($delete_by_values)) {
throw new RuntimeError("Variable at 'delete_by_values' is not an array.");
}
- $ar = array_filter($ar, function($v) use ($delete_by_values) { return !in_array($v, $delete_by_values); });
+ $ar = array_filter($ar, function ($v) use ($delete_by_values) {
+ return !in_array($v, $delete_by_values);
+ });
$keys = array_keys($ar);
}
diff --git a/src/ste/Scope.php b/src/ste/Scope.php
index 9326921..e312876 100644
--- a/src/ste/Scope.php
+++ b/src/ste/Scope.php
@@ -2,23 +2,25 @@
namespace kch42\ste;
-class Scope implements \ArrayAccess {
- private $parent = NULL;
+class Scope implements \ArrayAccess
+{
+ private $parent = null;
public $vars = array();
- private static function parse_name($name) {
+ private static function parse_name($name)
+ {
$remain = $name;
$fields = array();
- while($remain !== "") {
+ while ($remain !== "") {
$br_open = strpos($remain, '[');
- if($br_open === false) {
+ if ($br_open === false) {
$fields[] = $remain;
break;
}
$br_close = strpos($remain, ']', $br_open);
- if($br_close === false) {
+ if ($br_close === false) {
throw new RuntimeError("Invalid varname \"$name\". Missing closing \"]\".");
}
@@ -27,11 +29,11 @@ class Scope implements \ArrayAccess {
$field = substr($remain, $br_open+1, $br_close-$br_open-1);
$more = substr($remain, $br_close+1);
- if(strpos($field, '[') !== false) {
+ if (strpos($field, '[') !== false) {
throw new RuntimeError("A variable field must not contain a '[' character.");
}
- if((strlen($more) > 0) && ($more[0] !== '[')) {
+ if ((strlen($more) > 0) && ($more[0] !== '[')) {
// TODO: better error message, not very non-programmer friendly...
throw new RuntimeError("A variable name must be of format name('[' name ']')*.");
}
@@ -42,13 +44,14 @@ class Scope implements \ArrayAccess {
return $fields;
}
- private function &get_topvar_reference($name, $localonly) {
- if(array_key_exists($name, $this->vars)) {
+ private function &get_topvar_reference($name, $localonly)
+ {
+ if (array_key_exists($name, $this->vars)) {
$ref = &$this->vars[$name];
return $ref;
}
- if((!$localonly) && ($this->parent !== NULL)) {
+ if ((!$localonly) && ($this->parent !== null)) {
$ref = &$this->parent->get_topvar_reference($name, $localonly);
return $ref;
}
@@ -56,21 +59,22 @@ class Scope implements \ArrayAccess {
throw new VarNotInScope();
}
- public function &get_var_reference($name, $create_if_not_exist, $localonly=false) {
- $nullref = NULL;
+ public function &get_var_reference($name, $create_if_not_exist, $localonly=false)
+ {
+ $nullref = null;
$fields = self::parse_name($name);
- if(count($fields) == 0) {
+ if (count($fields) == 0) {
return $nullref; // TODO: or should we throw an exception here?
}
$first = $fields[0];
- $ref = NULL;
+ $ref = null;
try {
$ref = &$this->get_topvar_reference($first, $localonly);
- } catch(VarNotInScope $e) {
- if($create_if_not_exist) {
+ } catch (VarNotInScope $e) {
+ if ($create_if_not_exist) {
$this->vars[$first] = (count($fields) > 0) ? array() : "";
$ref = &$this->vars[$first];
} else {
@@ -78,19 +82,19 @@ class Scope implements \ArrayAccess {
}
}
- for($i = 1; $i < count($fields); $i++) {
+ for ($i = 1; $i < count($fields); $i++) {
$field = $fields[$i];
- if(!is_array($ref)) {
+ if (!is_array($ref)) {
return $nullref;
}
- if(!array_key_exists($field, $ref)) {
- if(!$create_if_not_exist) {
+ if (!array_key_exists($field, $ref)) {
+ if (!$create_if_not_exist) {
return $nullref;
}
- if($i < count($fields) - 1) {
+ if ($i < count($fields) - 1) {
$ref[$field] = array();
} else {
$ref[$field] = "";
@@ -103,22 +107,26 @@ class Scope implements \ArrayAccess {
return $ref;
}
- public function set_var_by_name($name, $val) {
+ public function set_var_by_name($name, $val)
+ {
$ref = &$this->get_var_reference($name, true);
$ref = $val;
}
- public function set_local_var($name, $val) {
+ public function set_local_var($name, $val)
+ {
$ref = &$this->get_var_reference($name, true, true);
$ref = $val;
}
- public function get_var_by_name($name) {
+ public function get_var_by_name($name)
+ {
$ref = $this->get_var_reference($name, false);
- return $ref === NULL ? "" : $ref;
+ return $ref === null ? "" : $ref;
}
- public function new_subscope() {
+ public function new_subscope()
+ {
$o = new self();
$o->parent = $this;
return $o;
@@ -126,21 +134,25 @@ class Scope implements \ArrayAccess {
/* implementing ArrayAccess */
- public function offsetSet($offset, $value) {
+ public function offsetSet($offset, $value)
+ {
$this->set_var_by_name($offset, $value);
}
- public function offsetGet($offset) {
+ public function offsetGet($offset)
+ {
return $this->get_var_by_name($offset);
}
- public function offsetExists($offset) {
+ public function offsetExists($offset)
+ {
try {
$this->get_topvar_reference($offset);
return true;
- } catch(VarNotInScope $e) {
+ } catch (VarNotInScope $e) {
return false;
}
}
- public function offsetUnset($offset) {
+ public function offsetUnset($offset)
+ {
unset($this->vars[$offset]);
}
}
diff --git a/src/ste/StorageAccess.php b/src/ste/StorageAccess.php
index 0798b41..e2e8727 100644
--- a/src/ste/StorageAccess.php
+++ b/src/ste/StorageAccess.php
@@ -11,7 +11,8 @@ namespace kch42\ste;
* A StorageAccess implementation is used to access the templates from any storage.
* This means, that you are not limited to store the Templates inside directories, you can also use a database or something else.
*/
-interface StorageAccess {
+interface StorageAccess
+{
/*
* Constants: Template modes
*
diff --git a/src/ste/StorageAccessFailure.php b/src/ste/StorageAccessFailure.php
index 4b319da..50dfc8a 100644
--- a/src/ste/StorageAccessFailure.php
+++ b/src/ste/StorageAccessFailure.php
@@ -2,4 +2,6 @@
namespace kch42\ste;
-abstract class StorageAccessFailure extends \Exception { }
+abstract class StorageAccessFailure extends \Exception
+{
+}
diff --git a/src/ste/TagNode.php b/src/ste/TagNode.php
index 8915c59..c1a14e5 100644
--- a/src/ste/TagNode.php
+++ b/src/ste/TagNode.php
@@ -2,11 +2,13 @@
namespace kch42\ste;
-class TagNode extends ASTNode {
+class TagNode extends ASTNode
+{
public $name;
public $params = array();
public $sub = array();
- public function __construct($tpl, $off, $name = "") {
+ public function __construct($tpl, $off, $name = "")
+ {
parent::__construct($tpl, $off);
$this->name = $name;
}
diff --git a/src/ste/TextNode.php b/src/ste/TextNode.php
index e6c7876..c68dd2f 100644
--- a/src/ste/TextNode.php
+++ b/src/ste/TextNode.php
@@ -2,10 +2,12 @@
namespace kch42\ste;
-class TextNode extends ASTNode {
+class TextNode extends ASTNode
+{
public $text;
- public function __construct($tpl, $off, $text = "") {
+ public function __construct($tpl, $off, $text = "")
+ {
parent::__construct($tpl, $off);
$this->text = $text;
}
-} \ No newline at end of file
+}
diff --git a/src/ste/Transcompiler.php b/src/ste/Transcompiler.php
index 4aadcdf..d223b53 100644
--- a/src/ste/Transcompiler.php
+++ b/src/ste/Transcompiler.php
@@ -9,15 +9,18 @@ namespace kch42\ste;
* Class: Transcompiler
* Contains the STE transcompiler. You'll only need this, if you want to manually transcompile a STE template.
*/
-class Transcompiler {
- private static $builtins = NULL;
+class Transcompiler
+{
+ private static $builtins = null;
- public static function tempvar($typ) {
+ public static function tempvar($typ)
+ {
return $typ . '_' . str_replace('.', '_', uniqid('', true));
}
- public static function init_builtins() {
- if(self::$builtins !== NULL) {
+ public static function init_builtins()
+ {
+ if (self::$builtins !== null) {
return;
}
@@ -42,23 +45,24 @@ class Transcompiler {
);
}
- private static function builtin_if($ast) {
+ private static function builtin_if($ast)
+ {
$output = "";
$condition = array();
- $then = NULL;
- $else = NULL;
+ $then = null;
+ $else = null;
- foreach($ast->sub as $node) {
- if(($node instanceof TagNode) and ($node->name == "then")) {
+ foreach ($ast->sub as $node) {
+ if (($node instanceof TagNode) and ($node->name == "then")) {
$then = $node->sub;
- } else if(($node instanceof TagNode) and ($node->name == "else")) {
+ } elseif (($node instanceof TagNode) and ($node->name == "else")) {
$else = $node->sub;
} else {
$condition[] = $node;
}
}
- if($then === NULL) {
+ if ($then === null) {
throw new ParseCompileError("self::Transcompile error: Missing <ste:then> in <ste:if>.", $ast->tpl, $ast->offset);
}
@@ -67,14 +71,15 @@ class Transcompiler {
$output .= "\$outputstack_i--;\nif(\$ste->evalbool(array_pop(\$outputstack)))\n{\n";
$output .= self::indent_code(self::_transcompile($then));
$output .= "\n}\n";
- if($else !== NULL) {
+ if ($else !== null) {
$output .= "else\n{\n";
$output .= self::indent_code(self::_transcompile($else));
$output .= "\n}\n";
}
return $output;
}
- private static function builtin_cmp($ast) {
+ private static function builtin_cmp($ast)
+ {
$operators = array(
array('eq', '=='),
array('neq', '!='),
@@ -86,42 +91,42 @@ class Transcompiler {
$code = "";
- if(isset($ast->params["var_b"])) {
+ if (isset($ast->params["var_b"])) {
list($val, $pre) = self::_transcompile($ast->params["var_b"], true);
$code .= $pre;
$b = '$ste->get_var_by_name(' . $val . ')';
- } else if(isset($ast->params["text_b"])) {
+ } elseif (isset($ast->params["text_b"])) {
list($b, $pre) = self::_transcompile($ast->params["text_b"], true);
$code .= $pre;
} else {
throw new ParseCompileError("self::Transcompile error: neiter var_b nor text_b set in <ste:cmp>.", $ast->tpl, $ast->offset);
}
- if(isset($ast->params["var_a"])) {
+ if (isset($ast->params["var_a"])) {
list($val, $pre) = self::_transcompile($ast->params["var_a"], true);
$code .= $pre;
$a = '$ste->get_var_by_name(' . $val . ')';
- } else if(isset($ast->params["text_a"])) {
+ } elseif (isset($ast->params["text_a"])) {
list($a, $pre) = self::_transcompile($ast->params["text_a"], true);
$code .= $pre;
} else {
throw new ParseCompileError("self::Transcompile error: neiter var_a nor text_a set in <ste:cmp>.", $ast->tpl, $ast->offset);
}
- if(!isset($ast->params["op"])) {
+ if (!isset($ast->params["op"])) {
throw new ParseCompileError("self::Transcompile error: op not given in <ste:cmp>.", $ast->tpl, $ast->offset);
}
- if((count($ast->params["op"]) == 1) and ($ast->params["op"][0] instanceof TextNode)) {
+ if ((count($ast->params["op"]) == 1) and ($ast->params["op"][0] instanceof TextNode)) {
/* Operator is known at compile time, this saves *a lot* of output code! */
$op = trim($ast->params["op"][0]->text);
- $op_php = NULL;
- foreach($operators as $v) {
- if($v[0] == $op) {
+ $op_php = null;
+ foreach ($operators as $v) {
+ if ($v[0] == $op) {
$op_php = $v[1];
break;
}
}
- if($op_php === NULL) {
+ if ($op_php === null) {
throw new ParseCompileError("self::Transcompile Error: Unknown operator in <ste:cmp>", $ast->tpl, $ast->offset);
}
$code .= "\$outputstack[\$outputstack_i] .= (($a) $op_php ($b)) ? 'yes' : '';\n";
@@ -129,49 +134,52 @@ class Transcompiler {
list($val, $pre) = self::_transcompile($ast->params["op"], true);
$code .= $pre . "switch(trim(" . $val . "))\n{\n\t";
$code .= implode("", array_map(
- function($op) use ($a,$b)
- {
+ function ($op) use ($a,$b) {
list($op_stetpl, $op_php) = $op;
return "case '$op_stetpl':\n\t\$outputstack[\$outputstack_i] .= (($a) $op_php ($b)) ? 'yes' : '';\n\tbreak;\n\t";
- }, $operators
- ));
+ },
+ $operators
+ ));
$code .= "default: throw new \\kch42\\ste\\RuntimeError('Unknown operator in <ste:cmp>.');\n}\n";
}
return $code;
}
- private static function builtin_not($ast) {
+ private static function builtin_not($ast)
+ {
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= self::_transcompile($ast->sub);
$code .= "\$outputstack_i--;\n\$outputstack[\$outputstack_i] .= (!\$ste->evalbool(array_pop(\$outputstack))) ? 'yes' : '';\n";
return $code;
}
- private static function builtin_even($ast) {
+ private static function builtin_even($ast)
+ {
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= self::_transcompile($ast->sub);
$code .= "\$outputstack_i--;\n\$tmp_even = array_pop(\$outputstack);\n\$outputstack[\$outputstack_i] .= (is_numeric(\$tmp_even) and (\$tmp_even % 2 == 0)) ? 'yes' : '';\n";
return $code;
}
- private static function builtin_for($ast) {
+ private static function builtin_for($ast)
+ {
$code = "";
$loopname = self::tempvar("forloop");
- if(empty($ast->params["start"])) {
+ if (empty($ast->params["start"])) {
throw new ParseCompileError("self::Transcompile error: Missing 'start' parameter in <ste:for>.", $ast->tpl, $ast->offset);
}
list($val, $pre) = self::_transcompile($ast->params["start"], true);
$code .= $pre;
$code .= "\$${loopname}_start = " . $val . ";\n";
- if(empty($ast->params["stop"])) {
+ if (empty($ast->params["stop"])) {
throw new ParseCompileError("self::Transcompile error: Missing 'end' parameter in <ste:for>.", $ast->tpl, $ast->offset);
}
list($val, $pre) = self::_transcompile($ast->params["stop"], true);
$code .= $pre;
$code .= "\$${loopname}_stop = " . $val . ";\n";
- $step = NULL; /* i.e. not known at compilation time */
- if(empty($ast->params["step"])) {
+ $step = null; /* i.e. not known at compilation time */
+ if (empty($ast->params["step"])) {
$step = 1;
- } else if((count($ast->params["step"]) == 1) and ($ast->params["step"][0] instanceof TextNode)) {
+ } elseif ((count($ast->params["step"]) == 1) and ($ast->params["step"][0] instanceof TextNode)) {
$step = $ast->params["step"][0]->text + 0;
} else {
list($val, $pre) = self::_transcompile($ast->params["step"], true);
@@ -179,7 +187,7 @@ class Transcompiler {
$code .= "\$${loopname}_step = " . $val . ";\n";
}
- if(!empty($ast->params["counter"])) {
+ if (!empty($ast->params["counter"])) {
list($val, $pre) = self::_transcompile($ast->params["counter"], true);
$code .= $pre;
$code .= "\$${loopname}_countername = " . $val . ";\n";
@@ -189,7 +197,7 @@ class Transcompiler {
$loopbody .= self::_transcompile($ast->sub);
$loopbody = self::indent_code("{\n" . self::loopbody(self::indent_code($loopbody)) . "\n}\n");
- if($step === NULL) {
+ if ($step === null) {
$code .= "if(\$${loopname}_step == 0)\n\tthrow new \\kch42\\ste\\RuntimeError('step can not be 0 in <ste:for>.');\n";
$code .= "if(\$${loopname}_step > 0)\n{\n";
$code .= "\tfor(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter <= \$${loopname}_stop; \$${loopname}_counter += \$${loopname}_step)\n";
@@ -198,9 +206,9 @@ class Transcompiler {
$code .= "\tfor(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter >= \$${loopname}_stop; \$${loopname}_counter += \$${loopname}_step)\n";
$code .= $loopbody;
$code .= "\n}\n";
- } else if($step == 0) {
+ } elseif ($step == 0) {
throw new ParseCompileError("self::Transcompile Error: step can not be 0 in <ste:for>.", $ast->tpl, $ast->offset);
- } else if($step > 0) {
+ } elseif ($step > 0) {
$code .= "for(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter <= \$${loopname}_stop; \$${loopname}_counter += $step)\n$loopbody\n";
} else {
$code .= "for(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter >= \$${loopname}_stop; \$${loopname}_counter += $step)\n$loopbody\n";
@@ -208,31 +216,32 @@ class Transcompiler {
return $code;
}
- private static function builtin_foreach($ast) {
+ private static function builtin_foreach($ast)
+ {
$loopname = self::tempvar("foreachloop");
$code = "";
- if(empty($ast->params["array"])) {
+ if (empty($ast->params["array"])) {
throw new ParseCompileError("self::Transcompile Error: array not given in <ste:foreach>.", $ast->tpl, $ast->offset);
}
list($val, $pre) = self::_transcompile($ast->params["array"], true);
$code .= $pre;
$code .= "\$${loopname}_arrayvar = " . $val . ";\n";
- if(empty($ast->params["value"])) {
+ if (empty($ast->params["value"])) {
throw new ParseCompileError("self::Transcompile Error: value not given in <ste:foreach>.", $ast->tpl, $ast->offset);
}
list($val, $pre) = self::_transcompile($ast->params["value"], true);
$code .= $pre;
$code .= "\$${loopname}_valuevar = " . $val . ";\n";
- if(!empty($ast->params["key"])) {
+ if (!empty($ast->params["key"])) {
list($val, $pre) = self::_transcompile($ast->params["key"], true);
$code .= $pre;
$code .= "\$${loopname}_keyvar = " . $val . ";\n";
}
- if(!empty($ast->params["counter"])) {
+ if (!empty($ast->params["counter"])) {
list($val, $pre) = self::_transcompile($ast->params["counter"], true);
$code .= $pre;
$code .= "\$${loopname}_countervar = " . $val . ";\n";
@@ -241,15 +250,15 @@ class Transcompiler {
$loopbody = "";
$code .= "\$${loopname}_array = \$ste->get_var_by_name(\$${loopname}_arrayvar);\n";
$code .= "if(!is_array(\$${loopname}_array))\n\t\$${loopname}_array = array();\n";
- if(!empty($ast->params["counter"])) {
+ if (!empty($ast->params["counter"])) {
$code .= "\$${loopname}_counter = -1;\n";
$loopbody .= "\$${loopname}_counter++;\n\$ste->set_var_by_name(\$${loopname}_countervar, \$${loopname}_counter);\n";
}
$loop = array();
$else = array();
- foreach($ast->sub as $node) {
- if(($node instanceof TagNode) && ($node->name == "else")) {
+ foreach ($ast->sub as $node) {
+ if (($node instanceof TagNode) && ($node->name == "else")) {
$else = array_merge($else, $node->sub);
} else {
$loop[] = $node;
@@ -257,14 +266,14 @@ class Transcompiler {
}
$loopbody .= "\$ste->set_var_by_name(\$${loopname}_valuevar, \$${loopname}_value);\n";
- if(!empty($ast->params["key"])) {
+ if (!empty($ast->params["key"])) {
$loopbody .= "\$ste->set_var_by_name(\$${loopname}_keyvar, \$${loopname}_key);\n";
}
$loopbody .= "\n";
$loopbody .= self::_transcompile($loop);
$loopbody = "{\n" . self::loopbody(self::indent_code($loopbody)) . "\n}\n";
- if(!empty($else)) {
+ if (!empty($else)) {
$code .= "if(empty(\$${loopname}_array))\n{\n";
$code .= self::indent_code(self::_transcompile($else));
$code .= "\n}\nelse ";
@@ -273,17 +282,21 @@ class Transcompiler {
return $code;
}
- private static function builtin_infloop($ast) {
+ private static function builtin_infloop($ast)
+ {
return "while(true)\n{\n" . self::indent_code(self::loopbody(self::indent_code(self::_transcompile($ast->sub)))) . "\n}\n";
}
- private static function builtin_break($ast) {
+ private static function builtin_break($ast)
+ {
return "throw new \\kch42\\ste\\BreakException();\n";
}
- private static function builtin_continue($ast) {
+ private static function builtin_continue($ast)
+ {
return "throw new \\kch42\\ste\\ContinueException();\n";
}
- private static function builtin_block($ast) {
- if(empty($ast->params["name"])) {
+ private static function builtin_block($ast)
+ {
+ if (empty($ast->params["name"])) {
throw new ParseCompileError("self::Transcompile Error: name missing in <ste:block>.", $ast->tpl, $ast->offset);
}
@@ -302,8 +315,9 @@ class Transcompiler {
return $code;
}
- private static function builtin_load($ast) {
- if(empty($ast->params["name"])) {
+ private static function builtin_load($ast)
+ {
+ if (empty($ast->params["name"])) {
throw new ParseCompileError("self::Transcompile Error: name missing in <ste:load>.", $ast->tpl, $ast->offset);
}
@@ -311,10 +325,11 @@ class Transcompiler {
$code .= "\$outputstack[\$outputstack_i] .= \$ste->load(" . $val . ");\n";
return $code;
}
- private static function builtin_mktag($ast) {
+ private static function builtin_mktag($ast)
+ {
$code = "";
- if(empty($ast->params["name"])) {
+ if (empty($ast->params["name"])) {
throw new ParseCompileError("self::Transcompile Error: name missing in <ste:mktag>.", $ast->tpl, $ast->offset);
}
@@ -323,7 +338,7 @@ class Transcompiler {
list($tagname, $tagname_pre) = self::_transcompile($ast->params["name"], true);
$usemandatory = "";
- if(!empty($ast->params["mandatory"])) {
+ if (!empty($ast->params["mandatory"])) {
$usemandatory = " use (\$mandatory_params)";
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= self::_transcompile($ast->params["mandatory"]);
@@ -341,11 +356,13 @@ class Transcompiler {
return $code;
}
- private static function builtin_tagcontent($ast) {
+ private static function builtin_tagcontent($ast)
+ {
return "\$outputstack[\$outputstack_i] .= \$sub(\$ste);";
}
- private static function builtin_set($ast) {
- if(empty($ast->params["var"])) {
+ private static function builtin_set($ast)
+ {
+ if (empty($ast->params["var"])) {
throw new ParseCompileError("self::Transcompile Error: var missing in <ste:set>.", $ast->tpl, $ast->offset);
}
@@ -359,8 +376,9 @@ class Transcompiler {
return $code;
}
- private static function builtin_setlocal($ast) {
- if(empty($ast->params["var"])) {
+ private static function builtin_setlocal($ast)
+ {
+ if (empty($ast->params["var"])) {
throw new ParseCompileError("self::Transcompile Error: var missing in <ste:set>.", $ast->tpl, $ast->offset);
}
@@ -374,15 +392,17 @@ class Transcompiler {
return $code;
}
- private static function builtin_get($ast) {
- if(empty($ast->params["var"])) {
+ private static function builtin_get($ast)
+ {
+ if (empty($ast->params["var"])) {
throw new ParseCompileError("self::Transcompile Error: var missing in <ste:get>.", $ast->tpl, $ast->offset);
}
- list($val, $pre) = self::_transcompile($ast->params["var"], true);
+ list($val, $pre) = self::_transcompile($ast->params["var"], true);
return "$pre\$outputstack[\$outputstack_i] .= \$ste->get_var_by_name(" . $val . ");";
}
- private static function builtin_calc($ast) {
+ private static function builtin_calc($ast)
+ {
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= self::_transcompile($ast->sub);
$code .= "\$outputstack_i--;\n\$outputstack[\$outputstack_i] .= \$ste->calc(array_pop(\$outputstack));\n";
@@ -390,39 +410,44 @@ class Transcompiler {
return $code;
}
- private static function indent_code($code) {
+ private static function indent_code($code)
+ {
return implode(
"\n",
- array_map(function($line) { return "\t$line"; }, explode("\n", $code))
+ array_map(function ($line) {
+ return "\t$line";
+ }, explode("\n", $code))
);
}
- private static function loopbody($code) {
+ private static function loopbody($code)
+ {
return "try\n{\n" . self::indent_code($code) . "\n}\ncatch(\\kch42\\ste\\BreakException \$e) { break; }\ncatch(\\kch42\\ste\\ContinueException \$e) { continue; }\n";
}
- private static function _transcompile($ast, $avoid_outputstack = false) { /* The real self::transcompile function, does not add boilerplate code. */
+ private static function _transcompile($ast, $avoid_outputstack = false)
+ { /* The real self::transcompile function, does not add boilerplate code. */
$code = "";
$text_and_var_buffer = array();
- foreach($ast as $node) {
- if($node instanceof TextNode) {
+ foreach ($ast as $node) {
+ if ($node instanceof TextNode) {
$text_and_var_buffer[] = '"' . Misc::escape_text($node->text) . '"';
- } else if($node instanceof VariableNode) {
+ } elseif ($node instanceof VariableNode) {
$text_and_var_buffer[] = $node->transcompile();
- } else if($node instanceof TagNode) {
- if(!empty($text_and_var_buffer)) {
- $code .= "\$outputstack[\$outputstack_i] .= " . implode (" . ", $text_and_var_buffer) . ";\n";
+ } elseif ($node instanceof TagNode) {
+ if (!empty($text_and_var_buffer)) {
+ $code .= "\$outputstack[\$outputstack_i] .= " . implode(" . ", $text_and_var_buffer) . ";\n";
$text_and_var_buffer = array();
}
- if(isset(self::$builtins[$node->name])) {
+ if (isset(self::$builtins[$node->name])) {
$code .= call_user_func(self::$builtins[$node->name], $node);
} else {
$paramarray = self::tempvar("parameters");
$code .= "\$$paramarray = array();\n";
- foreach($node->params as $pname => $pcontent) {
+ foreach ($node->params as $pname => $pcontent) {
list($pval, $pre) = self::_transcompile($pcontent, true);
$code .= $pre . "\$${paramarray}['" . Misc::escape_text($pname) . "'] = " . $pval . ";\n";
}
@@ -434,15 +459,15 @@ class Transcompiler {
}
}
- if($avoid_outputstack && ($code == "")) {
- return array(implode (" . ", $text_and_var_buffer), "");
+ if ($avoid_outputstack && ($code == "")) {
+ return array(implode(" . ", $text_and_var_buffer), "");
}
- if(!empty($text_and_var_buffer)) {
- $code .= "\$outputstack[\$outputstack_i] .= ". implode (" . ", $text_and_var_buffer) . ";\n";
+ if (!empty($text_and_var_buffer)) {
+ $code .= "\$outputstack[\$outputstack_i] .= ". implode(" . ", $text_and_var_buffer) . ";\n";
}
- if($avoid_outputstack) {
+ if ($avoid_outputstack) {
$tmpvar = self::tempvar("tmp");
$code = "\$outputstack[] = '';\n\$outputstack_i++;" . $code;
$code .= "\$$tmpvar = array_pop(\$outputstack);\n\$outputstack_i--;\n";
@@ -463,7 +488,8 @@ class Transcompiler {
* Returns:
* PHP code. The PHP code is an anonymous function expecting a <STECore> instance as its parameter and returns a string (everything that was not pached into a section).
*/
- public static function transcompile($ast) { /* self::Transcompile and add some boilerplate code. */
+ public static function transcompile($ast)
+ { /* self::Transcompile and add some boilerplate code. */
$boilerplate = "\$outputstack = array('');\n\$outputstack_i = 0;\n";
return "function(\$ste)\n{\n" . self::indent_code($boilerplate . self::_transcompile($ast) . "return array_pop(\$outputstack);") . "\n}";
}
diff --git a/src/ste/VarNotInScope.php b/src/ste/VarNotInScope.php
index 179d07a..6dc5eda 100644
--- a/src/ste/VarNotInScope.php
+++ b/src/ste/VarNotInScope.php
@@ -2,4 +2,6 @@
namespace kch42\ste;
-class VarNotInScope extends \Exception {}
+class VarNotInScope extends \Exception
+{
+}
diff --git a/src/ste/VariableNode.php b/src/ste/VariableNode.php
index 18bb6a4..d03fdce 100644
--- a/src/ste/VariableNode.php
+++ b/src/ste/VariableNode.php
@@ -2,19 +2,21 @@
namespace kch42\ste;
-class VariableNode extends ASTNode {
+class VariableNode extends ASTNode
+{
public $name;
public $arrayfields = array();
- public function transcompile() {
+ public function transcompile()
+ {
$varaccess = '@$ste->scope[' . (is_numeric($this->name) ? $this->name : '"' . Misc::escape_text($this->name) . '"'). ']';
- foreach($this->arrayfields as $af) {
- if((count($af) == 1) and ($af[0] instanceof TextNode) and is_numeric($af[0]->text)) {
+ foreach ($this->arrayfields as $af) {
+ if ((count($af) == 1) and ($af[0] instanceof TextNode) and is_numeric($af[0]->text)) {
$varaccess .= '[' . $af->text . ']';
} else {
- $varaccess .= '[' . implode(".", array_map(function($node) {
- if($node instanceof TextNode) {
+ $varaccess .= '[' . implode(".", array_map(function ($node) {
+ if ($node instanceof TextNode) {
return "\"" . Misc::escape_text($node->text) . "\"";
- } else if($node instanceof VariableNode) {
+ } elseif ($node instanceof VariableNode) {
return $node->transcompile();
}
}, $af)). ']';
diff --git a/ste.php b/ste.php
index 35e2084..72d6eca 100644
--- a/ste.php
+++ b/ste.php
@@ -38,22 +38,52 @@ require_once(__DIR__ . "/src/ste/STECore.php");
/* Providing "proxy classes", so old applications can continue using the ste namespace */
-class ASTNode extends \kch42\ste\ASTNode {}
-class TagNode extends \kch42\ste\TagNode {}
-class TextNode extends \kch42\ste\TextNode {}
-class VariableNode extends \kch42\ste\VariableNode {}
-class ParseCompileError extends \kch42\ste\ParseCompileError {}
-class RuntimeError extends \kch42\ste\RuntimeError {}
-class FatalRuntimeError extends \kch42\ste\FatalRuntimeError {}
-class StorageAccessFailure extends \kch42\ste\StorageAccessFailure {}
-class CantLoadTemplate extends \kch42\ste\CantLoadTemplate {}
-class CantSaveTemplate extends \kch42\ste\CantSaveTemplate {}
-class FilesystemStorageAccess extends \kch42\ste\FilesystemStorageAccess {}
-class Parser extends \kch42\ste\Parser {}
-class Transcompiler extends \kch42\ste\Transcompiler {}
-class STECore extends \kch42\ste\STECore {}
-
-interface StorageAccess extends \kch42\ste\StorageAccess {}
+class ASTNode extends \kch42\ste\ASTNode
+{
+}
+class TagNode extends \kch42\ste\TagNode
+{
+}
+class TextNode extends \kch42\ste\TextNode
+{
+}
+class VariableNode extends \kch42\ste\VariableNode
+{
+}
+class ParseCompileError extends \kch42\ste\ParseCompileError
+{
+}
+class RuntimeError extends \kch42\ste\RuntimeError
+{
+}
+class FatalRuntimeError extends \kch42\ste\FatalRuntimeError
+{
+}
+class StorageAccessFailure extends \kch42\ste\StorageAccessFailure
+{
+}
+class CantLoadTemplate extends \kch42\ste\CantLoadTemplate
+{
+}
+class CantSaveTemplate extends \kch42\ste\CantSaveTemplate
+{
+}
+class FilesystemStorageAccess extends \kch42\ste\FilesystemStorageAccess
+{
+}
+class Parser extends \kch42\ste\Parser
+{
+}
+class Transcompiler extends \kch42\ste\Transcompiler
+{
+}
+class STECore extends \kch42\ste\STECore
+{
+}
+
+interface StorageAccess extends \kch42\ste\StorageAccess
+{
+}
/* We also put the storage mode constants here (they were outside of the interface before for some reason I can't remember...) */
diff --git a/steloader.php b/steloader.php
index 8c4c36f..5e490be 100644
--- a/steloader.php
+++ b/steloader.php
@@ -6,9 +6,10 @@
* Use a full-fledged PSR-3 autoloader (e.g. the composer loader) for production!
*/
-function autoload_ste($cl) {
+function autoload_ste($cl)
+{
$path = explode("\\", $cl);
- if(($path[0] == "kch42") && ($path[1] == "ste")) {
+ if (($path[0] == "kch42") && ($path[1] == "ste")) {
require_once(__DIR__ . "/src/ste/" . $path[2] . ".php");
}
}
diff --git a/tests/test.php b/tests/test.php
index fcfac0e..15453b0 100644
--- a/tests/test.php
+++ b/tests/test.php
@@ -5,14 +5,17 @@ require("code.php");
use \kch42\ste;
-class TestStorage implements ste\StorageAccess {
- public function load($tpl, &$mode) {
+class TestStorage implements ste\StorageAccess
+{
+ public function load($tpl, &$mode)
+ {
$mode = ste\StorageAccess::MODE_SOURCE;
return file_get_contents($tpl);
}
- public function save($tpl, $data, $mode) {
- if($mode != ste\StorageAccess::MODE_TRANSCOMPILED) {
+ public function save($tpl, $data, $mode)
+ {
+ if ($mode != ste\StorageAccess::MODE_TRANSCOMPILED) {
return;
}
diff --git a/tests/test_array/code.php b/tests/test_array/code.php
index 1e02e20..b524c15 100644
--- a/tests/test_array/code.php
+++ b/tests/test_array/code.php
@@ -1,6 +1,7 @@
<?php
-function test_func($ste) {
+function test_func($ste)
+{
$ste->vars["foo"] = array(
"a" => array(
"blabla" => "OK"
diff --git a/tests/test_blocks/code.php b/tests/test_blocks/code.php
index 2e68d2d..25e7f00 100644
--- a/tests/test_blocks/code.php
+++ b/tests/test_blocks/code.php
@@ -1,5 +1,5 @@
<?php
-function test_func($ste) {
-
+function test_func($ste)
+{
}
diff --git a/tests/test_closure/code.php b/tests/test_closure/code.php
index 2e68d2d..25e7f00 100644
--- a/tests/test_closure/code.php
+++ b/tests/test_closure/code.php
@@ -1,5 +1,5 @@
<?php
-function test_func($ste) {
-
+function test_func($ste)
+{
}
diff --git a/tests/test_escapes/code.php b/tests/test_escapes/code.php
index d1a64c7..a1904c8 100644
--- a/tests/test_escapes/code.php
+++ b/tests/test_escapes/code.php
@@ -1,7 +1,8 @@
<?php
-function test_func($ste) {
- $ste->register_tag("my_echo", function($ste, $params, $sub) {
+function test_func($ste)
+{
+ $ste->register_tag("my_echo", function ($ste, $params, $sub) {
return $params["text"];
});
}
diff --git a/tests/test_foreach/code.php b/tests/test_foreach/code.php
index 1dc5ab9..60ad311 100644
--- a/tests/test_foreach/code.php
+++ b/tests/test_foreach/code.php
@@ -1,6 +1,7 @@
<?php
-function test_func($ste) {
+function test_func($ste)
+{
$ste->vars["foo"] = array(
"a" => array("a" => 100, "b" => 200),
"b" => array("a" => 1, "b" => 2),
diff --git a/tests/test_getset/code.php b/tests/test_getset/code.php
index 398686b..722af1e 100644
--- a/tests/test_getset/code.php
+++ b/tests/test_getset/code.php
@@ -1,5 +1,6 @@
<?php
-function test_func($ste) {
+function test_func($ste)
+{
$ste->vars["foo"] = "bar";
}
diff --git a/tests/test_loop/code.php b/tests/test_loop/code.php
index 2e68d2d..25e7f00 100644
--- a/tests/test_loop/code.php
+++ b/tests/test_loop/code.php
@@ -1,5 +1,5 @@
<?php
-function test_func($ste) {
-
+function test_func($ste)
+{
}
diff --git a/tests/test_mktag/code.php b/tests/test_mktag/code.php
index 2e68d2d..25e7f00 100644
--- a/tests/test_mktag/code.php
+++ b/tests/test_mktag/code.php
@@ -1,5 +1,5 @@
<?php
-function test_func($ste) {
-
+function test_func($ste)
+{
}
diff --git a/tests/test_pseudotags/code.php b/tests/test_pseudotags/code.php
index 2e68d2d..25e7f00 100644
--- a/tests/test_pseudotags/code.php
+++ b/tests/test_pseudotags/code.php
@@ -1,5 +1,5 @@
<?php
-function test_func($ste) {
-
+function test_func($ste)
+{
}
diff --git a/tests/test_recursive/code.php b/tests/test_recursive/code.php
index d897479..96b967b 100644
--- a/tests/test_recursive/code.php
+++ b/tests/test_recursive/code.php
@@ -1,5 +1,6 @@
<?php
-function test_func($ste) {
+function test_func($ste)
+{
$ste->mute_runtime_errors = false;
}
diff --git a/tests/test_scoping/code.php b/tests/test_scoping/code.php
index 2e68d2d..25e7f00 100644
--- a/tests/test_scoping/code.php
+++ b/tests/test_scoping/code.php
@@ -1,5 +1,5 @@
<?php
-function test_func($ste) {
-
+function test_func($ste)
+{
}
diff --git a/tests/test_short/code.php b/tests/test_short/code.php
index 2e68d2d..25e7f00 100644
--- a/tests/test_short/code.php
+++ b/tests/test_short/code.php
@@ -1,5 +1,5 @@
<?php
-function test_func($ste) {
-
+function test_func($ste)
+{
}
diff --git a/tests/test_simple/code.php b/tests/test_simple/code.php
index e68faac..2712e2b 100644
--- a/tests/test_simple/code.php
+++ b/tests/test_simple/code.php
@@ -1,5 +1,6 @@
<?php
-function test_func($ste) {
+function test_func($ste)
+{
$ste->vars["foo"] = "World";
}
diff --git a/tests/test_tagname/code.php b/tests/test_tagname/code.php
index 6001358..e934989 100644
--- a/tests/test_tagname/code.php
+++ b/tests/test_tagname/code.php
@@ -2,7 +2,8 @@
use kch42\ste\STECore;
-function test_func(STECore $ste) {
+function test_func(STECore $ste)
+{
$names = array(
"foo",
"ab_cd",
@@ -13,8 +14,9 @@ function test_func(STECore $ste) {
foreach ($names as $name) {
$ste->register_tag(
$name,
- function ($ste, $params, $sub) use ($name) { return $name; }
+ function ($ste, $params, $sub) use ($name) {
+ return $name;
+ }
);
}
-
}