From cd20955c9fdb06514ad73561ac73c939ce0759bd Mon Sep 17 00:00:00 2001 From: Vitaliy Filippov Date: Fri, 9 Jan 2015 18:58:50 +0300 Subject: [PATCH] round() function for template --- VMXTemplate/Compiler.pm | 2 ++ VMXTemplate/Utils.pm | 10 +++++++++- template.parser.php | 4 +++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/VMXTemplate/Compiler.pm b/VMXTemplate/Compiler.pm index d69a114..3e9cde3 100644 --- a/VMXTemplate/Compiler.pm +++ b/VMXTemplate/Compiler.pm @@ -118,6 +118,7 @@ my $functionSafeness = { mod => Q_ALWAYS_NUM, min => Q_IF_ALL_PASS, max => Q_IF_ALL_PASS, + round => Q_ALWAYS_NUM, log => Q_ALWAYS_NUM, even => Q_ALWAYS_NUM, odd => Q_ALWAYS_NUM, @@ -278,6 +279,7 @@ sub function_mod { fmop('%', @_) } # min, max sub function_min { (grep { $_->[1] ne 'i' } @_ ? 'str_' : '')."min(".join(', ', map { $_->[0] } @_).")" } sub function_max { (grep { $_->[1] ne 'i' } @_ ? 'str_' : '')."max(".join(', ', map { $_->[0] } @_).")" } +sub function_round { "round($_[1])" } # logarithm sub function_log { "log($_[1])" } # is the argument even/odd? diff --git a/VMXTemplate/Utils.pm b/VMXTemplate/Utils.pm index de234cb..c1fb091 100644 --- a/VMXTemplate/Utils.pm +++ b/VMXTemplate/Utils.pm @@ -12,7 +12,7 @@ our @EXPORT = qw( timestamp plural_ru strlimit htmlspecialchars urlencode urldecode strip_tags strip_unsafe_tags addcslashes requote quotequote sql_quote regex_replace str_replace array_slice array_div encode_json trim html_pbr array_items utf8on - exec_subst exec_pairs exec_is_array exec_get exec_cmp min max str_min str_max var_dump + exec_subst exec_pairs exec_is_array exec_get exec_cmp min max str_min str_max round var_dump ); use constant { @@ -406,6 +406,14 @@ sub str_max return $r; } +# round +sub round +{ + my $i = int($_[0]); + my $a = $_[0]-$i; + return $a >= 0.5 ? $i+1 : ($a <= -0.5 ? $i-1 : $i); +} + # Quote strings without transforming UTF-8 to \x{...} sub _dumper_qquote { diff --git a/template.parser.php b/template.parser.php index 7c38a18..8e5851b 100644 --- a/template.parser.php +++ b/template.parser.php @@ -92,6 +92,7 @@ class VMXTemplateCompiler 'mod' => self::Q_ALWAYS, 'min' => self::Q_IF_ALL, 'max' => self::Q_IF_ALL, + 'round' => self::Q_ALWAYS, 'log' => self::Q_ALWAYS, 'even' => self::Q_ALWAYS, 'odd' => self::Q_ALWAYS, @@ -287,9 +288,10 @@ $code function function_div() { $a = func_get_args(); return self::fmop('/', $a); } function function_mod($a,$b) { return "(($a) % ($b))"; } - /* минимум и максимум */ + /* минимум и максимум, округление */ function function_min() { $a = func_get_args(); return "min([ ".implode(', ', $a)." ])"; } function function_max() { $a = func_get_args(); return "max([ ".implode(', ', $a)." ])"; } + function function_round($a) { return "round($a)"; } /* логарифм */ function function_log($e) { return "log($e)"; }