4

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

2
  • i depends how complex are your "expressions", simplest cases could be validated using regular expressions, for complex cases you need to build state machine (or use external library). how about you give us some examples ? Commented May 11, 2016 at 17:48
  • hmm ,so i guess you dont REALLY need processing of complex expressions, so i think in your case better solution is to offer to user more strict client based (javascript) filter where he would select from array(table) columns, operator and value ... (and he could add more of these filters) Commented May 11, 2016 at 21:14

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a side note: as of Symfony 4.2 the class SyntaxError is still there but RuntimeException is used / thrown instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.