tags:

views:

56

answers:

2

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.

+2  A: 

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

Mark Baker
+1. i am going to try it out.. any idea what happens if i pass php functions to the parser?
pinaki
If you specifically need PHP functions (e.g. string manipulation or whatever) rather than simply mathematical functions, then it's pretty easy to add these to the built in function list
Mark Baker
great.. seems like it would do... will give it a try and see where it can lead... thanks for the quick replies..
pinaki
this doesnt work for conditional operators.. only seems to evaluate mathematical operations.. any ideas?
pinaki
Add the conditional operators to the $ops, $ops_r and $ops_p arrays in the nfx() method, then expand the logic of the if (in_array($token, array('+', '-', '*', '/', '^'))) { test in the pfx() method to perform the appropriate comparison and push the result back onto the stack.... it's pretty straightforward, though you might need to tweak the nfx() method logic slightly to test for operators like >= that are 2 characters rather than 1
Mark Baker
great.. just saw your comment.. i was already working on similar lines and it works perfect.. thanks a lot.. accepting this as the correct answer..
pinaki
+1  A: 

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.

Gordon
+1 seems interesting, not sure if I can use it since this might require major changes... thanks anyway for the answer, i will pursure it and see where it leads..
pinaki