Compare commits

...

8 Commits

Author SHA1 Message Date
Simon Wisselink 78d259d3b9 Merge branch 'release/5.8.0' 2026-02-15 15:27:15 +01:00
Simon Wisselink 4ed569c674 version bump 2026-02-15 15:27:13 +01:00
Simon Wisselink a46478d0cb changelogs 2026-02-15 15:26:43 +01:00
Simon Wisselink 5487e31c4b Add support for Backed Enums (#1171)
* Add support for Backed Enums
Fixes #1012

Also added docs (and docs for matches operator)
2026-02-15 15:23:55 +01:00
Simon Wisselink 12ce28e265 Regex matches operator (#1169)
* Regex matches operator support
2026-02-15 14:44:48 +01:00
Simon Wisselink 139797a165 Support for Laravel Collections style object chaining (#1168)
* Support for Laravel Collections style object chaining for objects return from function calls implemented as modifiers
Fixes #1151

* explain publishing docs
2026-02-11 00:02:52 +01:00
hirosan 6709d000cd Fix static analysis warnings for isDot() and remove deprecated APC support (#1164)
* Fix static analysis warnings for isDot()
* Remove deprecated APC support
* Remove redundant isDot() check and fix static analysis warnings
2026-01-08 11:21:57 +01:00
Simon Wisselink aa6edc3c0b Document missing inline implementation. Fixed #1152 (#1156) 2025-12-21 22:58:11 +01:00
22 changed files with 1878 additions and 1344 deletions
+7
View File
@@ -6,6 +6,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [5.8.0] - 2026-02-15
- Added support for Backed Enums for php versions >= 8.1 [#1171](https://github.com/smarty-php/smarty/pull/1171)
- Added support for new 'matches' operator doing regex matching [#1169](https://github.com/smarty-php/smarty/pull/1169)
- Update documentation to clarify that include inline is currently not implemented in Smarty v5 [#1152](https://github.com/smarty-php/smarty/issues/1152)
- Support for Laravel Collections style object chaining for objects return from function calls implemented as modifiers [#1151](https://github.com/smarty-php/smarty/issues/1151)
## [5.7.0] - 2025-11-19
- PHP 8.5 support
+2
View File
@@ -115,5 +115,7 @@ If you are a maintainer, you can publish the document using [mike](https://githu
mike deploy 5.x
```
Then, push the `gh-pages` branch.
## Attribution
This guide is based on the **contributing.md**. [Make your own](https://contributing.md/)!
@@ -50,6 +50,120 @@ separated from surrounding elements by spaces. Note that items listed in
| is \[not\] odd by | | $a is not odd by $b | \[not\] an odd grouping | ($a / $b) % 2 != 0 |
| is in | | $a is in $b | exists in array | in_array($a, $b) |
| is \[not\] in | | $a is not in $b | does not exist in array | !in_array($a, $b) |
| matches | | $a matches $b | regex pattern match | preg_match($b, $a) |
## Regex Matching Operator
The `matches` operator allows you to test if a string matches a regular expression pattern.
### Basic Usage
```smarty
{if "hello" matches "/^[a-z]+$/"}
String matches the pattern!
{/if}
{if $email matches "/^[^@]+@[^@]+\.[^@]+$/"}
Valid email format
{else}
Invalid email format
{/if}
```
### Using Variables
```smarty
{$pattern = '/^[a-zA-Z0-9]{8,}$/'}
{if $password matches $pattern}
Password meets requirements
{else}
Password must be at least 8 alphanumeric characters
{/if}
```
### Pattern Modifiers
The `matches` operator supports all standard PHP regex modifiers:
```smarty
{* Case insensitive matching *}
{if "HELLO" matches "/hello/i"}
Matches (case insensitive)
{/if}
{* Multiline mode *}
{if "line1\nline2" matches "/line2$/m"}
Matches in multiline mode
{/if}
{* Dot matches newlines *}
{if "hello\nworld" matches "/hello.world/s"}
Matches with dotall modifier
{/if}
```
### Complex Conditions
The `matches` operator can be combined with other operators:
```smarty
{if $username matches "/^[a-z]+$/" && $username|length > 3}
Valid username
{else}
Username must be lowercase letters and at least 4 characters
{/if}
{if $input matches "/^[0-9]+$/" || $input matches "/^[a-z]+$/"}
Input is either numeric or lowercase letters
{else}
Invalid input format
{/if}
```
### Practical Examples
**Email Validation:**
```smarty
{if $email matches "/^[^@\s]+@[^@\s]+\.[^@\s]+$/"}
Valid email address
{else}
Please enter a valid email address
{/if}
```
**Password Strength:**
```smarty
{if $password matches "/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/"}
Strong password
{else}
Password must contain uppercase, lowercase, numbers and be at least 8 characters
{/if}
```
**URL Validation:**
```smarty
{if $url matches "/^https?:\/\/(www\.)?[a-z0-9\-]+(\.[a-z]{2,})+/i"}
Valid URL format
{else}
Please enter a valid URL
{/if}
```
**Numeric Validation:**
```smarty
{if $input matches "/^[0-9]+$/"}
Valid numeric input
{else}
Please enter numbers only
{/if}
```
### Notes
- The `matches` operator uses PHP's `preg_match()` function internally
- Pattern delimiters must be valid regex delimiters (typically `/`)
- Invalid patterns will cause PHP warnings but won't break template execution
- For complex regex patterns, consider using variables for better readability
## Ternary
You can use the `?:` (or ternary) operator to test one expression and present the value
@@ -47,11 +47,13 @@ available within the included template.
## Option Flags
| Name | Description |
|---------|--------------------------------------------------------------------------------------|
| nocache | Disables caching of this subtemplate |
| caching | Enable caching of this subtemplate |
| inline | If set, merge the compile-code of the subtemplate into the compiled calling template |
| Name | Description |
|-----------|--------------------------------------------------------------------------------------|
| nocache | Disables caching of this subtemplate |
| caching | Enable caching of this subtemplate |
| inline \* | If set, merge the compile-code of the subtemplate into the compiled calling template |
\* The `inline` option flag is currently not implemented in Smarty v5. Using it will not trigger an error, however.
## Examples
```smarty
@@ -123,4 +123,89 @@ this will output:
```html
name: Zaphod Beeblebrox<br />
email: zaphod@slartibartfast.example.com<br />
```
```
## Backed Enums (PHP 8.1+)
Smarty supports accessing properties of [backed enums](https://www.php.net/manual/en/language.enumerations.backed.php) introduced in PHP 8.1.
### Accessing Enum Properties
You can access the `name` and `value` properties of backed enum cases:
```smarty
{* Access enum case properties *}
<option id="{MyEnum::Foo->name}">{MyEnum::Foo->value}</option>
```
### Complete Example
```php
<?php
use Smarty\Smarty;
// Define a backed enum
enum Status: string {
case Active = 'active';
case Inactive = 'inactive';
case Pending = 'pending';
}
$smarty = new Smarty();
$smarty->assign('currentStatus', Status::Active);
$smarty->display('template.tpl');
```
`template.tpl`:
```smarty
{* Display enum properties *}
Current status: {$currentStatus->name} (value: {$currentStatus->value})
{* Use in HTML attributes *}
<select name="status">
<option value="{Status::Active->value}" {if $currentStatus->name === 'Active'}selected{/if}>Active</option>
<option value="{Status::Inactive->value}" {if $currentStatus->name === 'Inactive'}selected{/if}>Inactive</option>
<option value="{Status::Pending->value}" {if $currentStatus->name === 'Pending'}selected{/if}>Pending</option>
</select>
```
This would output:
```html
Current status: Active (value: active)
<select name="status">
<option value="active" selected>Active</option>
<option value="inactive">Inactive</option>
<option value="pending">Pending</option>
</select>
```
### Integer-backed Enums
Integer-backed enums work the same way:
```php
<?php
enum Priority: int {
case Low = 1;
case Medium = 2;
case High = 3;
}
$smarty->assign('priority', Priority::High);
```
```smarty
{* Access integer enum properties *}
Priority level: {$priority->value} ({$priority->name})
```
Output:
```html
Priority level: 3 (High)
```
> **Note**: Backed enum support requires PHP 8.1 or higher. The enum must be registered or available in the current namespace.
+2
View File
@@ -22,6 +22,8 @@ Some of Smarty's features:
- [Template Inheritance](api/inheritance.md) for
easy management of template content.
- [Plugin](api/extending/introduction.md) architecture
- Regex pattern matching with the [`matches`](designers/language-basic-syntax/language-syntax-operators.md#regex-matching-operator) operator
- Support for PHP 8.1+ [backed enums](designers/language-variables/language-assigned-variables.md#backed-enums-php-81)
## Separation of presentation from application code
- This means templates can certainly contain logic under the condition
+19
View File
@@ -8,6 +8,25 @@ It allows you to write **templates**, using **variables**, **modifiers**, **func
<p>
The number of pixels is: {math equation="x * y" x=$height y=$width}.
</p>
<p>
{if $email matches "/^[^@]+@[^@]+\.[^@]+$/"}
Valid email address
{else}
Please enter a valid email
{/if}
</p>
```
```html
<h1>Hello world</h1>
<p>
The number of pixels is: 307200.
</p>
<p>
Valid email address
</p>
```
When this template is rendered, with the value "Hello world" for the variable $title, 640 for $width,
+2 -8
View File
@@ -127,8 +127,6 @@ class File extends Base
&& (!function_exists('ini_get') || strlen(ini_get('opcache.restrict_api'))) < 1
) {
opcache_invalidate($_template->getCached()->filepath, true);
} elseif (function_exists('apc_compile_file')) {
apc_compile_file($_template->getCached()->filepath);
}
$cached = $_template->getCached();
$cached->timestamp = $cached->exists = is_file($cached->filepath);
@@ -223,10 +221,8 @@ class File extends Base
$_filepath = (string)$_file;
// directory ?
if ($_file->isDir()) {
if (!$_cache->isDot()) {
// delete folder if empty
@rmdir($_file->getPathname());
}
// delete folder if empty
@rmdir($_file->getPathname());
} else {
// delete only php files
if (substr($_filepath, -4) !== '.php') {
@@ -279,8 +275,6 @@ class File extends Base
&& (!function_exists('ini_get') || strlen(ini_get("opcache.restrict_api")) < 1)
) {
opcache_invalidate($_filepath, true);
} elseif (function_exists('apc_delete_file')) {
apc_delete_file($_filepath);
}
}
}
+44 -38
View File
@@ -160,6 +160,7 @@ class TemplateLexer
'LOGOP' => '"<", "==" ... logical operator',
'TLOGOP' => '"lt", "eq" ... logical operator; "is div by" ... if condition',
'SCOND' => '"is even" ... if condition',
'MATCHES' => '"matches" regex operator',
);
/**
@@ -567,7 +568,7 @@ class TemplateLexer
public function yylex3()
{
if (!isset($this->yy_global_pattern3)) {
$this->yy_global_pattern3 = $this->replace("/\G(\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal)|\G([\"])|\G('[^'\\\\]*(?:\\\\.[^'\\\\]*)*')|\G([$][0-9]*[a-zA-Z_]\\w*)|\G([$])|\G(\\s+is\\s+(not\\s+)?in\\s+)|\G(\\s+as\\s+)|\G(\\s+to\\s+)|\G(\\s+step\\s+)|\G(\\s+instanceof\\s+)|\G(\\s*([!=][=]{1,2}|[<][=>]?|[>][=]?|[&|]{2})\\s*)|\G(\\s+(eq|ne|neq|gt|ge|gte|lt|le|lte|mod|and|or|xor)\\s+)|\G(\\s+is\\s+(not\\s+)?(odd|even|div)\\s+by\\s+)|\G(\\s+is\\s+(not\\s+)?(odd|even))|\G([!]\\s*|not\\s+)|\G([(](int(eger)?|bool(ean)?|float|double|real|string|binary|array|object)[)]\\s*)|\G(\\s*[(]\\s*)|\G(\\s*[)])|\G(\\[\\s*)|\G(\\s*\\])|\G(\\s*[-][>]\\s*)|\G(\\s*[=][>]\\s*)|\G(\\s*[=]\\s*)|\G(([+]|[-]){2})|\G(\\s*([+]|[-])\\s*)|\G(\\s*([*]{1,2}|[%\/^&]|[<>]{2})\\s*)|\G([@])|\G(array\\s*[(]\\s*)|\G([#])|\G(\\s+[0-9]*[a-zA-Z_][a-zA-Z0-9_\-:]*\\s*[=]\\s*)|\G(([0-9]*[a-zA-Z_]\\w*)?(\\\\[0-9]*[a-zA-Z_]\\w*)+)|\G([0-9]*[a-zA-Z_]\\w*)|\G(\\d+)|\G([`])|\G([|][@]?)|\G([.])|\G(\\s*[,]\\s*)|\G(\\s*[;]\\s*)|\G([:]{2})|\G(\\s*[:]\\s*)|\G(\\s*[?]\\s*)|\G(0[xX][0-9a-fA-F]+)|\G(\\s+)|\G([\S\s])/isS");
$this->yy_global_pattern3 = $this->replace("/\G(\\s*SMARTYrdel)|\G((SMARTYldel)SMARTYal)|\G([\"])|\G('[^'\\\\]*(?:\\\\.[^'\\\\]*)*')|\G([$][0-9]*[a-zA-Z_]\\w*)|\G([$])|\G(\\s+is\\s+(not\\s+)?in\\s+)|\G(\\s+matches\\s+)|\G(\\s+as\\s+)|\G(\\s+to\\s+)|\G(\\s+step\\s+)|\G(\\s+instanceof\\s+)|\G(\\s*([!=][=]{1,2}|[<][=>]?|[>][=]?|[&|]{2})\\s*)|\G(\\s+(eq|ne|neq|gt|ge|gte|lt|le|lte|mod|and|or|xor)\\s+)|\G(\\s+is\\s+(not\\s+)?(odd|even|div)\\s+by\\s+)|\G(\\s+is\\s+(not\\s+)?(odd|even))|\G([!]\\s*|not\\s+)|\G([(](int(eger)?|bool(ean)?|float|double|real|string|binary|array|object)[)]\\s*)|\G(\\s*[(]\\s*)|\G(\\s*[)])|\G(\\[\\s*)|\G(\\s*\\])|\G(\\s*[-][>]\\s*)|\G(\\s*[=][>]\\s*)|\G(\\s*[=]\\s*)|\G(([+]|[-]){2})|\G(\\s*([+]|[-])\\s*)|\G(\\s*([*]{1,2}|[%\/^&]|[<>]{2})\\s*)|\G([@])|\G(array\\s*[(]\\s*)|\G([#])|\G(\\s+[0-9]*[a-zA-Z_][a-zA-Z0-9_\-:]*\\s*[=]\\s*)|\G(([0-9]*[a-zA-Z_]\\w*)?(\\\\[0-9]*[a-zA-Z_]\\w*)+)|\G([0-9]*[a-zA-Z_]\\w*)|\G(\\d+)|\G([`])|\G([|][@]?)|\G([.])|\G(\\s*[,]\\s*)|\G(\\s*[;]\\s*)|\G([:]{2})|\G(\\s*[:]\\s*)|\G(\\s*[?]\\s*)|\G(0[xX][0-9a-fA-F]+)|\G(\\s+)|\G([\S\s])/isS");
}
if (!isset($this->dataLength)) {
$this->dataLength = strlen($this->data);
@@ -662,119 +663,124 @@ class TemplateLexer
public function yy_r3_10()
{
$this->token = \Smarty\Parser\TemplateParser::TP_AS;
$this->token = \Smarty\Parser\TemplateParser::TP_MATCHES;
}
public function yy_r3_11()
{
$this->token = \Smarty\Parser\TemplateParser::TP_TO;
$this->token = \Smarty\Parser\TemplateParser::TP_AS;
}
public function yy_r3_12()
{
$this->token = \Smarty\Parser\TemplateParser::TP_STEP;
$this->token = \Smarty\Parser\TemplateParser::TP_TO;
}
public function yy_r3_13()
{
$this->token = \Smarty\Parser\TemplateParser::TP_INSTANCEOF;
$this->token = \Smarty\Parser\TemplateParser::TP_STEP;
}
public function yy_r3_14()
{
$this->token = \Smarty\Parser\TemplateParser::TP_INSTANCEOF;
}
public function yy_r3_15()
{
$this->token = \Smarty\Parser\TemplateParser::TP_LOGOP;
}
public function yy_r3_16()
public function yy_r3_17()
{
$this->token = \Smarty\Parser\TemplateParser::TP_SLOGOP;
}
public function yy_r3_18()
public function yy_r3_19()
{
$this->token = \Smarty\Parser\TemplateParser::TP_TLOGOP;
}
public function yy_r3_21()
public function yy_r3_22()
{
$this->token = \Smarty\Parser\TemplateParser::TP_SINGLECOND;
}
public function yy_r3_24()
public function yy_r3_25()
{
$this->token = \Smarty\Parser\TemplateParser::TP_NOT;
}
public function yy_r3_25()
public function yy_r3_26()
{
$this->token = \Smarty\Parser\TemplateParser::TP_TYPECAST;
}
public function yy_r3_29()
public function yy_r3_30()
{
$this->token = \Smarty\Parser\TemplateParser::TP_OPENP;
}
public function yy_r3_30()
public function yy_r3_31()
{
$this->token = \Smarty\Parser\TemplateParser::TP_CLOSEP;
}
public function yy_r3_31()
public function yy_r3_32()
{
$this->token = \Smarty\Parser\TemplateParser::TP_OPENB;
}
public function yy_r3_32()
public function yy_r3_33()
{
$this->token = \Smarty\Parser\TemplateParser::TP_CLOSEB;
}
public function yy_r3_33()
public function yy_r3_34()
{
$this->token = \Smarty\Parser\TemplateParser::TP_PTR;
}
public function yy_r3_34()
public function yy_r3_35()
{
$this->token = \Smarty\Parser\TemplateParser::TP_APTR;
}
public function yy_r3_35()
public function yy_r3_36()
{
$this->token = \Smarty\Parser\TemplateParser::TP_EQUAL;
}
public function yy_r3_36()
public function yy_r3_37()
{
$this->token = \Smarty\Parser\TemplateParser::TP_INCDEC;
}
public function yy_r3_38()
public function yy_r3_39()
{
$this->token = \Smarty\Parser\TemplateParser::TP_UNIMATH;
}
public function yy_r3_40()
public function yy_r3_41()
{
$this->token = \Smarty\Parser\TemplateParser::TP_MATH;
}
public function yy_r3_42()
public function yy_r3_43()
{
$this->token = \Smarty\Parser\TemplateParser::TP_AT;
}
public function yy_r3_43()
public function yy_r3_44()
{
$this->token = \Smarty\Parser\TemplateParser::TP_ARRAYOPEN;
}
public function yy_r3_44()
public function yy_r3_45()
{
$this->token = \Smarty\Parser\TemplateParser::TP_HATCH;
}
public function yy_r3_45()
public function yy_r3_46()
{
// resolve conflicts with shorttag and right_delimiter starting with '='
@@ -786,73 +792,73 @@ class TemplateLexer
$this->token = \Smarty\Parser\TemplateParser::TP_ATTR;
}
}
public function yy_r3_46()
public function yy_r3_47()
{
$this->token = \Smarty\Parser\TemplateParser::TP_NAMESPACE;
}
public function yy_r3_49()
public function yy_r3_50()
{
$this->token = \Smarty\Parser\TemplateParser::TP_ID;
}
public function yy_r3_50()
public function yy_r3_51()
{
$this->token = \Smarty\Parser\TemplateParser::TP_INTEGER;
}
public function yy_r3_51()
public function yy_r3_52()
{
$this->token = \Smarty\Parser\TemplateParser::TP_BACKTICK;
$this->yypopstate();
}
public function yy_r3_52()
public function yy_r3_53()
{
$this->token = \Smarty\Parser\TemplateParser::TP_VERT;
}
public function yy_r3_53()
public function yy_r3_54()
{
$this->token = \Smarty\Parser\TemplateParser::TP_DOT;
}
public function yy_r3_54()
public function yy_r3_55()
{
$this->token = \Smarty\Parser\TemplateParser::TP_COMMA;
}
public function yy_r3_55()
public function yy_r3_56()
{
$this->token = \Smarty\Parser\TemplateParser::TP_SEMICOLON;
}
public function yy_r3_56()
public function yy_r3_57()
{
$this->token = \Smarty\Parser\TemplateParser::TP_DOUBLECOLON;
}
public function yy_r3_57()
public function yy_r3_58()
{
$this->token = \Smarty\Parser\TemplateParser::TP_COLON;
}
public function yy_r3_58()
public function yy_r3_59()
{
$this->token = \Smarty\Parser\TemplateParser::TP_QMARK;
}
public function yy_r3_59()
public function yy_r3_60()
{
$this->token = \Smarty\Parser\TemplateParser::TP_HEX;
}
public function yy_r3_60()
public function yy_r3_61()
{
$this->token = \Smarty\Parser\TemplateParser::TP_SPACE;
}
public function yy_r3_61()
public function yy_r3_62()
{
$this->token = \Smarty\Parser\TemplateParser::TP_TEXT;
+5
View File
@@ -160,6 +160,7 @@ class TemplateLexer
'LOGOP' => '"<", "==" ... logical operator',
'TLOGOP' => '"lt", "eq" ... logical operator; "is div by" ... if condition',
'SCOND' => '"is even" ... if condition',
'MATCHES' => '"matches" regex operator',
);
/**
@@ -325,6 +326,7 @@ class TemplateLexer
tlop = ~\s+is\s+(not\s+)?(odd|even|div)\s+by\s+~
scond = ~\s+is\s+(not\s+)?(odd|even)~
isin = ~\s+is\s+(not\s+)?in\s+~
matches = ~\s+matches\s+~
as = ~\s+as\s+~
to = ~\s+to\s+~
step = ~\s+step\s+~
@@ -469,6 +471,9 @@ class TemplateLexer
isin {
$this->token = \Smarty\Parser\TemplateParser::TP_ISIN;
}
matches {
$this->token = \Smarty\Parser\TemplateParser::TP_MATCHES;
}
as {
$this->token = \Smarty\Parser\TemplateParser::TP_AS;
}
+1206 -1136
View File
File diff suppressed because it is too large Load Diff
+30 -6
View File
@@ -681,6 +681,11 @@ expr(res) ::= expr(e1) isin(c) value(v). {
res = c . e1.',(array)'.v.')';
}
// regex matching
expr(res) ::= expr(e1) matchop(c) value(e2). {
res = c . e2 . ',' . e1 . ') ';
}
// null coalescing
nullcoalescing(res) ::= expr(v) QMARK QMARK expr(e2). {
res = v.' ?? '.e2;
@@ -1062,12 +1067,22 @@ object(res) ::= varindexed(vi) objectchain(oc). {
}
}
// optional objectchain - empty
optobjectchain(res) ::= . {
res = '';
}
// optional objectchain - present
optobjectchain(res) ::= objectchain(oc). {
res = oc;
}
// single element
objectchain(res) ::= objectelement(oe). {
res = oe;
}
// chain of elements
// chain of elements
objectchain(res) ::= objectchain(oc) objectelement(oe). {
res = oc.oe;
}
@@ -1111,7 +1126,7 @@ objectelement(res)::= PTR method(f). {
//
// function
//
function(res) ::= ns1(f) OPENP variablelist(v) CLOSEP. {
function(res) ::= ns1(f) OPENP variablelist(v) CLOSEP optobjectchain(oc). {
if (f == 'isset') {
res = '(true';
@@ -1125,15 +1140,15 @@ function(res) ::= ns1(f) OPENP variablelist(v) CLOSEP. {
res .= ' && (' . $value . ' !== null)';
}
}
res .= ')';
res .= ')' . oc;
} elseif (f == 'empty') {
if (count(v) != 1) {
throw new CompilerException("Invalid number of arguments for empty. empty expects at exactly one parameter.");
}
if (is_array(v[0])) {
res .= '( !' . v[0][0] . ' || empty(' . v[0][1] . '))';
res = '( !' . v[0][0] . ' || empty(' . v[0][1] . '))' . oc;
} else {
res = 'false == ' . v[0];
res = 'false == ' . v[0] . oc;
}
} else {
$p = array();
@@ -1144,7 +1159,7 @@ function(res) ::= ns1(f) OPENP variablelist(v) CLOSEP. {
$p[] = $value;
}
}
res = $this->compiler->compileModifierInExpression(f, $p);
res = $this->compiler->compileModifierInExpression(f, $p) . oc;
}
}
@@ -1244,6 +1259,11 @@ static_class_access(res) ::= ID(v). {
res = array(v, '');
}
// static class constant with object chain
static_class_access(res) ::= ID(v) objectchain(oc). {
res = array(v, oc);
}
// static class variables
static_class_access(res) ::= DOLLARID(v) arrayindex(a). {
res = array(v, a, 'property');
@@ -1303,6 +1323,10 @@ scond(res) ::= SINGLECOND(o). {
res = $scond[$op];
}
matchop(res) ::= MATCHES(o). {
res = 'preg_match(';
}
//
// ARRAY element assignment
//
+3 -7
View File
@@ -54,7 +54,7 @@ class Smarty extends \Smarty\TemplateBase {
/**
* smarty version
*/
const SMARTY_VERSION = '5.7.0';
const SMARTY_VERSION = '5.8.0';
/**
* define caching modes
@@ -1344,10 +1344,8 @@ class Smarty extends \Smarty\TemplateBase {
}
$_filepath = (string)$_file;
if ($_file->isDir()) {
if (!$_compile->isDot()) {
// delete folder if empty
@rmdir($_file->getPathname());
}
// delete folder if empty
@rmdir($_file->getPathname());
} else {
// delete only php files
if (substr($_filepath, -4) !== '.php') {
@@ -1385,8 +1383,6 @@ class Smarty extends \Smarty\TemplateBase {
&& (!function_exists('ini_get') || strlen(ini_get('opcache.restrict_api')) < 1)
) {
opcache_invalidate($_filepath, true);
} elseif (function_exists('apc_delete_file')) {
apc_delete_file($_filepath);
}
}
}
-2
View File
@@ -251,8 +251,6 @@ class Compiled extends GeneratedPhpFile {
&& (!function_exists('ini_get') || strlen(ini_get("opcache.restrict_api")) < 1)
) {
opcache_invalidate($this->filepath, true);
} elseif (function_exists('apc_compile_file')) {
apc_compile_file($this->filepath);
}
}
if (defined('HHVM_VERSION')) {
+2 -4
View File
@@ -291,10 +291,8 @@ KEY `name` (`name`)
}
// directory ?
if ($file->isDir()) {
if (!$ri->isDot()) {
// delete folder if empty
@rmdir($file->getPathname());
}
// delete folder if empty
@rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
@@ -1,31 +0,0 @@
<?php
/**
* Smarty PHPunit tests for cache resource Apc
*
* @author Uwe Tews
*/
include_once __DIR__ . '/../Memcache/CacheResourceCustomMemcacheTest.php';
include_once __DIR__ . '/../_shared/PHPunitplugins/cacheresource.apctest.php';
/**
* class for cache resource file tests
*
*
* @preserveGlobalState disabled
*
*/
class CacheResourceCustomApcTest extends CacheResourceCustomMemcacheTest
{
public function setUp(): void
{
if (!function_exists('apc_cache_info') || ini_get('apc.enable_cli')) {
$this->markTestSkipped('APC cache not available');
}
$this->setUpSmarty(__DIR__);
parent::setUp();
$this->smarty->setCachingType('apc');
$this->smarty->registerCacheResource('apc', new Smarty_CacheResource_Apctest());
}
}
@@ -1,33 +0,0 @@
<?php
use Smarty\Smarty;
use Smarty\Template;
use Smarty\Template\Cached;
require_once __DIR__ . '/../../../__shared/cacheresources/cacheresource.apc.php';
class Smarty_CacheResource_Apctest extends Smarty_CacheResource_Apc
{
public $lockTime = 0;
public function hasLock(Smarty $smarty, Cached $cached)
{
if ($this->lockTime) {
$this->lockTime--;
if (!$this->lockTime) {
$this->releaseLock($smarty, $cached);
}
}
return parent::hasLock($smarty, $cached);
}
public function get(Template $_template)
{
$this->contents = array();
$this->timestamps = array();
$t = $this->getContent($_template);
return $t ? $t : null;
}
}
@@ -64,6 +64,21 @@ class StaticClassAccessTest extends PHPUnit_Smarty
$this->assertEquals('3', $this->smarty->fetch($tpl));
}
/**
* test static class constant chain
*/
public function testRegisteredBackedEnum()
{
if (PHP_VERSION_ID < 80100) {
$this->markTestSkipped('Enums only available after PHP >= 8.1');
return;
} else {
$this->smarty->registerClass('RegisteredBackedEnum', MyBackedEnum::class);
$tpl = $this->smarty->createTemplate('eval:{RegisteredBackedEnum::A->value}');
$this->assertEquals('3', $this->smarty->fetch($tpl));
}
}
/**
* test static class method
*/
@@ -134,3 +149,7 @@ class mystaticclass
return $i * $i;
}
}
if (PHP_VERSION_ID >= 80100) {
eval('enum MyBackedEnum: int { case A = 3; }');
}
@@ -0,0 +1,208 @@
<?php
/**
* Smarty PHPunit tests for object chain functionality after function calls
* Tests the new feature: {$x = collect($data)->filter()->values()->toJson()}
*
* @author Smarty Vibe
*/
/**
* Helper class to simulate a chainable collection object
*/
class ChainableCollection
{
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function filter()
{
$this->data = array_filter($this->data);
return $this;
}
public function values()
{
$this->data = array_values($this->data);
return $this;
}
public function toJson()
{
return json_encode($this->data);
}
public function toArray()
{
return $this->data;
}
public function count()
{
return count($this->data);
}
}
/**
* Modifier plugin that returns a chainable object (simulates collect())
*/
function smarty_modifier_collect($data)
{
return new ChainableCollection($data);
}
/**
* Modifier plugin that returns an object with methods
*/
function smarty_modifier_create_object($value = null)
{
return new class {
public function getName() {
return 'TestObject';
}
public function getNext() {
return new class {
public function getValue() {
return 'ChainedValue';
}
};
}
};
}
/**
* class for function object chain tests
*
* @preserveGlobalState disabled
*
*/
class FunctionObjectChainTest extends PHPUnit_Smarty
{
public function setUp(): void
{
$this->setUpSmarty(__DIR__);
// Register modifier plugins that return chainable objects
// These are called like functions: {collect($data)}
$this->smarty->registerPlugin(\Smarty\Smarty::PLUGIN_MODIFIER, 'collect', 'smarty_modifier_collect');
$this->smarty->registerPlugin(\Smarty\Smarty::PLUGIN_MODIFIER, 'create_object', 'smarty_modifier_create_object');
}
public function testInit()
{
$this->cleanDirs();
}
/**
* Test the NEW feature: function call followed by method chain
* This is the core test for: {$x = collect($data)->filter()->values()->toJson()}
*/
public function testFunctionCallWithMethodChain()
{
$data = [1, 2, 0, 3, null, 4, '', 5];
$this->smarty->assign('data', $data);
// Test the new syntax: function()->method()->method()->method()
$result = $this->smarty->fetch('string:{collect($data)->filter()->values()->toJson()}');
$this->assertEquals('[1,2,3,4,5]', $result);
}
/**
* Test function call with method chain assigned to a variable
* This tests: {$x = collect($data)->filter()->values()->toJson()}
*/
public function testFunctionCallWithMethodChainAssignment()
{
$data = ['a', 'b', '', 'c', null, 'd'];
$this->smarty->assign('data', $data);
// Test assignment with chained methods
$result = $this->smarty->fetch('string:{$result = collect($data)->filter()->values()->toJson()}{$result}');
$this->assertEquals('["a","b","c","d"]', $result);
}
/**
* Test function call with single method chain
*/
public function testFunctionCallWithSingleMethod()
{
$data = [1, 2, 3];
$this->smarty->assign('data', $data);
$result = $this->smarty->fetch('string:{collect($data)->count()}');
$this->assertEquals('3', $result);
}
/**
* Test function call with nested method chains
*/
public function testFunctionCallWithNestedChain()
{
$result = $this->smarty->fetch('string:{create_object("")->getNext()->getValue()}');
$this->assertEquals('ChainedValue', $result);
}
/**
* Test that old syntax still works (two-step process)
*/
public function testOldSyntaxStillWorks()
{
$data = [1, 2, 0, 3];
$this->smarty->assign('data', $data);
// Old syntax: assign to variable first, then chain
$result = $this->smarty->fetch('string:{$x = collect($data)}{$x->filter()->values()->toJson()}');
$this->assertEquals('[1,2,3]', $result);
}
/**
* Test object chain functionality using template file
*/
public function testFunctionObjectChainFromTemplateFile()
{
$data = ['foo', '', 'bar', null, 'baz'];
$this->smarty->assign('data', $data);
$result = $this->smarty->fetch('test_function_chain.tpl');
// Expected: JSON of filtered array and count
$this->assertStringContainsString('["foo","bar","baz"]', $result);
$this->assertStringContainsString('3', $result);
}
/**
* Test complex chaining with multiple operations
* This demonstrates the power of the new feature
*/
public function testComplexChaining()
{
$data = [1, 2, 0, 3, '', 4, null, 5, false, 6];
$this->smarty->assign('data', $data);
// Complex chain: collect -> filter -> values -> toArray
$result = $this->smarty->fetch('string:{$filtered = collect($data)->filter()->values()->toArray()}{$filtered|@json_encode}');
$this->assertEquals('[1,2,3,4,5,6]', $result);
}
/**
* Test that demonstrates the benefit: one line vs multiple lines
*/
public function testNewSyntaxVsOldSyntax()
{
$data = [10, 20, 0, 30];
$this->smarty->assign('data', $data);
// NEW syntax (single line)
$new = $this->smarty->fetch('string:{collect($data)->filter()->count()}');
// OLD syntax (multiple steps)
$old = $this->smarty->fetch('string:{$temp = collect($data)}{$temp = $temp->filter()}{$temp->count()}');
// Both should produce the same result
$this->assertEquals('3', $new);
$this->assertEquals($new, $old);
}
}
@@ -0,0 +1,4 @@
{* Test template for NEW function object chain feature *}
{* Test: function()->method()->method()->method() *}
{collect($data)->filter()->values()->toJson()}
{collect($data)->filter()->count()}
@@ -0,0 +1,118 @@
<?php
require_once __DIR__ . '/../../../../Bootstrap.php';
class MatchesOperatorTest extends PHPUnit_Smarty {
public function setUp(): void
{
$this->setUpSmarty(__DIR__);
}
public function testInit()
{
$this->cleanDirs();
}
/**
* Test basic regex matching functionality
*/
public function testBasicMatches() {
// Test string matching pattern
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "hello" matches "/^[a-z]+$/"}Match!{else}No match{/if}'));
// Test no match
$this->assertEquals('No match', $this->smarty->fetch('string:{if "123" matches "/^[a-z]+$/"}Match!{else}No match{/if}'));
// Test with variables
$this->smarty->assign('name', 'hello');
$this->smarty->assign('pattern', '/^[a-z]+$/');
$this->assertEquals('Match!', $this->smarty->fetch('string:{if $name matches $pattern}Match!{else}No match{/if}'));
// Test no match with variables
$this->smarty->assign('number', '123');
$this->assertEquals('No match', $this->smarty->fetch('string:{if $number matches $pattern}Match!{else}No match{/if}'));
}
/**
* Test different regex patterns
*/
public function testDifferentPatterns() {
// Test numeric pattern
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "123" matches "/^[0-9]+$/"}Match!{else}No match{/if}'));
// Test email pattern
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "test@example.com" matches "/^[^@]+@[^@]+\.[^@]+$/"}Match!{else}No match{/if}'));
// Test case insensitive pattern
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "Hello" matches "/hello/i"}Match!{else}No match{/if}'));
// Test pattern with special characters
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "hello-world" matches "/^[a-z-]+$/"}Match!{else}No match{/if}'));
}
/**
* Test regex patterns with modifiers
*/
public function testPatternModifiers() {
// Test case insensitive modifier
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "HELLO" matches "/hello/i"}Match!{else}No match{/if}'));
// Test multiline modifier
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "hello\nworld" matches "/world$/m"}Match!{else}No match{/if}'));
// Test dotall modifier
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "hello\nworld" matches "/hello.world/s"}Match!{else}No match{/if}'));
}
/**
* Test complex expressions with matches operator
*/
public function testComplexExpressions() {
// Test with logical AND
$this->smarty->assign('name', 'hello');
$this->smarty->assign('pattern', '/^[a-z]+$/');
$this->smarty->assign('length', 5);
$this->assertEquals('Valid!', $this->smarty->fetch('string:{if $name matches $pattern && $length > 3}Valid!{else}Invalid{/if}'));
// Test with logical OR
$this->assertEquals('Valid!', $this->smarty->fetch('string:{if $name matches $pattern || $length < 3}Valid!{else}Invalid{/if}'));
// Test in elseif
$this->assertEquals('ElseIf!', $this->smarty->fetch('string:{if $name matches "/^[0-9]+$/"}No{elseif $name matches $pattern}ElseIf!{else}Else{/if}'));
// Test in while loop condition (should work with constant patterns)
$result = $this->smarty->fetch('string:{assign var="i" value=0}{while $i < 2 && "test" matches "/test/"}{$i}{assign var="i" value=$i+1}{/while}');
$this->assertEquals('01', $result);
}
/**
* Test edge cases and error handling
*/
public function testEdgeCases() {
// Test with empty string
$this->assertEquals('No match', $this->smarty->fetch('string:{if "" matches "/.+/"}Match!{else}No match{/if}'));
// Test with complex pattern
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "abc123" matches "/^[a-z]+[0-9]+$/"}Match!{else}No match{/if}'));
// Test with single character pattern
$this->assertEquals('Match!', $this->smarty->fetch('string:{if "a" matches "/a/"}Match!{else}No match{/if}'));
}
/**
* Test that invalid patterns still work (they will cause PHP warnings but not break the template)
* Note: This test is commented out because invalid patterns cause PHP warnings that fail the test
* In production, invalid patterns would cause warnings but the template would still execute
*/
/*
public function testInvalidPatterns() {
// This will cause a PHP warning but should not break the template execution
$this->smarty->assign('invalid_pattern', 'not-a-valid-pattern');
$this->smarty->assign('name', 'hello');
// The template should execute and reach the else branch due to the invalid pattern
$result = $this->smarty->fetch('string:{if $name matches $invalid_pattern}Match!{else}No match{/if}');
$this->assertEquals('No match', $result);
}
*/
}
@@ -1,73 +0,0 @@
<?php
/**
* APC CacheResource
* CacheResource Implementation based on the KeyValueStore API to use
* memcache as the storage resource for Smarty's output caching.
* *
*
* @author Uwe Tews
*/
class Smarty_CacheResource_Apc extends \Smarty\Cacheresource\KeyValueStore
{
/**
* Read values for a set of keys from cache
*
* @param array $keys list of keys to fetch
*
* @return array list of values with the given keys used as indexes
* @return boolean true on success, false on failure
*/
protected function read(array $keys)
{
$_res = array();
$res = apc_fetch($keys);
foreach ($res as $k => $v) {
$_res[ $k ] = $v;
}
return $_res;
}
/**
* Save values for a set of keys to cache
*
* @param array $keys list of values to save
* @param int $expire expiration time
*
* @return boolean true on success, false on failure
*/
protected function write(array $keys, $expire = null)
{
foreach ($keys as $k => $v) {
apc_store($k, $v, $expire);
}
return true;
}
/**
* Remove values from cache
*
* @param array $keys list of keys to delete
*
* @return boolean true on success, false on failure
*/
protected function delete(array $keys)
{
foreach ($keys as $k) {
apc_delete($k);
}
return true;
}
/**
* Remove *all* values from cache
*
* @return boolean true on success, false on failure
*/
protected function purge()
{
return apc_clear_cache('user');
}
}