pinaki
pinaki

Reputation: 5473

Alternative for 'eval() uating' a condition

In the legacy codebase that I am working on, there is a condition evaluator which accepts user input to build a condition. This condition is then evaluated at run-time using php eval(). What is the best way to resolve this without using eval.

For e.g. I have a condition "1>0" entered by the user in the UI. This has to evaluated and the result (true in this case) returned. Any suggestions?

Let know if the problem seems vague, I would try and explain better.

Upvotes: 2

Views: 846

Answers (2)

Gordon
Gordon

Reputation: 317197

I'd say the pattern most suited for this would be the Specification pattern.

In computer programming, the specification pattern is a particular software design pattern, whereby business logic can be recombined by chaining the business logic together using boolean logic.

However, that approach would require you to write a parser for the input given by your users to safely transform the conditions to the specification instances. Depending on the complexity of conditions allowed, this might not be an easy task.

You could achieve the same by creating lambda functions with create_function for the assertions, but that is as insecure as using eval when it comes to user input.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212522

The evalMath parser over on PHPClasses provides a safe framework for evaluating this type of expression.

Upvotes: 2

Related Questions