【发布时间】:2017-02-22 05:56:03
【问题描述】:
我有一个包含对象和数组的复杂对象。在这里发布数据对象太大了(在我的类中定义为 $this->data )。我还有一个带有简单“{{name.something}}”模板表达式的配置文件。我正在尝试编写一个简单的表达式解析器来解析配置字符串,例如“{{patient.firstname}}”。
示例表达式:
{{patient.firstname}}、{{patient->firstname}} 甚至 {{patient.customfields[0].customfieldvalue}}
下面的代码似乎运行良好。现在我已经让它工作了,我质疑 eval() 函数的用法和安全性。配置文件不包含任何用户输入的数据。这段代码安全吗?有没有办法在没有 eval() 的情况下重写它?
<?php
// Note - This is only part of the class.
/*
* Parse Template Value Expressions
* Allows complex object data to be used. Examples:
* {{patient.firstname}}, {{patient->firstname}} or even {{patient.customfields[0].customfieldvalue}}
*/
private function _parseDataValue($value = '') {
// Parse Template Expressions: Allows data input to be used {{name}}, {{name1.name2}}, etc
if ($value != '' && preg_match('/\{\{([a-z0-9\-_\[\]\>\.]+)\}\}/i', trim($value))) {
$value = preg_replace_callback('/\{\{([a-z0-9\-_\[\]\>\.]+)\}\}/i',
array(&$this, '_buildDataCallback'), trim($value));
}
return $value;
}
/*
* Parse Template Value Expressions Callback Method
*/
private function _buildDataCallback($matches) {
$out = '';
if (isset($matches[1])) {
$var = $matches[1];
@eval("\$out = \$this->data->$var;");
}
return $out;
}
?>
【问题讨论】:
标签: php parsing templates eval