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.
I'd say the pattern most suited for this would be the Specification pattern.
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 usingeval
when it comes to user input.The evalMath parser over on PHPClasses provides a safe framework for evaluating this type of expression.