Alternative for 'eval() uating' a condition

岁酱吖の 提交于 2019-12-22 13:30:39

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3511589/alternative-for-eval-uating-a-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!