PHP code example of uuf6429 / expression-language-tplstring

1. Go to this page and download the library: Download uuf6429/expression-language-tplstring library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

uuf6429 / expression-language-tplstring example snippets


$el = new \uuf6429\ExpressionLanguage\ExpressionLanguageWithTplStr();
$result = $el->evaluate('`hello ${name}!`', ['name' => 'mars']);
assert($result === 'hello mars!');

use uuf6429\ExpressionLanguage\TemplateStringTranslatorTrait;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage as SymfonyExpressionLanguage;
use Symfony\Component\ExpressionLanguage\ParsedExpression as SymfonyParsedExpression;

class MyCustomExpressionLanguage
{
    use TemplateStringTranslatorTrait;

    private SymfonyExpressionLanguage $base;

    public function __construct()
    {
        $this->base = new SymfonyExpressionLanguage();
    }

    public function compile($expression, array $names = []): string
    {
        return $this->base->compile($this->processTemplateStrings($expression), $names);
    }

    public function evaluate($expression, array $values = [])
    {
        return $this->base->evaluate($this->processTemplateStrings($expression), $values);
    }
}

$el = new MyCustomExpressionLanguage();
$result = $el->evaluate('`hello ${name}!`', ['name' => 'world']);
assert($result === 'hello world!');

$el = new \uuf6429\ExpressionLanguage\ExpressionLanguageWithTplStr();
$result = $el->evaluate(
    '`Hello ${user.isMember ? `VIP ${user.name}` : \'Guest\'}!`',
    [
        'user' => (object)[
            'isMember' => true,
            'name' => 'John',
        ],
    ]
);
assert($result === 'Hello VIP John!');

$el = new \uuf6429\ExpressionLanguage\ExpressionLanguageWithTplStr();
try {
    $el->evaluate('`hello ${name');
} catch (\Symfony\Component\ExpressionLanguage\SyntaxError $e) {
    assert($e->getMessage() === 'Expected "}" around position 13 for expression ``hello ${name`.');
}