Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a symfony expression language expression

I'm making a system where users can enter they own expressions. I've searched all of the internet and I can't seem to find a sample of how I could validate the user entered expression before executing it.

Is there a "standard way" or "best practice" to validate user entered expressions or do I have to roll my own validation?

EDIT

I just want to allow a user to filter a table (array), so the expressions I guess wouldn't be overly complex.

so for an array with headers like array('id', 'firstName', 'lastName', 'docId', 'profit'); I'm expecting expressions like: row.id < 2 and row.profit <= 500

like image 732
Cesar Avatar asked Oct 26 '25 12:10

Cesar


1 Answers

The Symfony/ExpressionLanguage package have a SyntaxError class, and throws this exception if exist error in expression.

Control error:

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\SyntaxError;

$expressionLanguage = new ExpressionLanguage();

try {
    $expressionLanguage->evaluate('1 + b.foo');
} catch (SyntaxError $e) {
    // Error
}

But, we can not control error by types:

  1. Invalid syntax
  2. Variable not found
  3. Unexpected token
  4. Function not found
  5. etc...

As solution (bad idea), you can control types via text in exception.

like image 106
ZhukV Avatar answered Oct 28 '25 01:10

ZhukV