“eval() uating”的替代方案一个条件

发布于 2024-09-14 20:20:45 字数 202 浏览 4 评论 0原文

在我正在处理的遗留代码库中,有一个条件评估器,它接受用户输入来构建条件。然后使用 php eval() 在运行时评估此条件。在不使用 eval 的情况下解决此问题的最佳方法是什么?

例如,我有用户在 UI 中输入的条件“1>0”。必须对此进行评估并返回结果(在本例中为 true)。有什么建议吗?

如果问题看起来含糊不清,请告诉我,我会尽力解释得更好。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡墨 2024-09-21 20:20:45

PHPClasses 上的 evalMath 解析器 提供了评估此类表达式的安全框架。

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

相对绾红妆 2024-09-21 20:20:45

我想说最适合这种情况的模式是规范模式

在计算机编程中,规范模式是一种特定的软件设计模式,可以通过使用布尔逻辑将业务逻辑链接在一起来重新组合业务逻辑。

但是,该方法需要您为用户给出的输入编写一个解析器,以安全地将条件转换为规范实例。根据允许的条件的复杂程度,这可能不是一件容易的事。

您可以通过为断言使用 create_function 创建 lambda 函数来实现相同的目的,但这与在用户输入方面使用 eval 一样不安全。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文