我有一个自定义验证规则模块,该模块实质上允许用户设置CSV验证。我的问题是我到达了这个数组:
Array(
[field_name] => 'is_int(324230435)',
[some_other_field] => 'strlen("some str") > 25'
)
我做了一些研究,发现了eval()
函数。
引用:How to use string in IF condition in PHP
但是,由于安全性问题,我真的不想使用eval()
(参考:When is eval evil in php?)
尽管没有严格说出eval是邪恶的,但我仍然希望有替代方法。
我对eval()
的使用是否过于谨慎-也许我应该逃避使用eval()
还是有更好的方法?
答案 0 :(得分:0)
仅需使用@deceze答案和建议即可使用Symfony的ExpressionLanguage组件。
我通过Composer将其安装到我的项目中,并认为对于绊倒帖子的任何人来说,查看它是否有效(以及与我的问题有关)可能会有所帮助:
# build array for testing rows against rules
$test = [];
# foreach csv row
foreach ($csv as $keey => $row)
{
# 10000s of rows, just for simplicity - break after 3
if ($keey == 0) {continue;}
if ($keey >= 3) {continue;}
# get array keys for
$keys = array_keys($row);
foreach ($keys as $key)
{
# if row key is in the $conditions array, add to $test array for testing
if (in_array($key, array_map('strtolower', array_keys($conditions)))) {
$conditionType = array_keys($conditions[$key]);
$conditionType = $conditionType[0];
if ($conditionType === 'condition_suffix') {
$brokenCondition = explode(' ', $conditions[$key][$conditionType]);
# build array to pass into ->evaluate()
$test[$key]['evaluate'] = 'field '. $brokenCondition[0] .' required'; # expression to actually test
$test[$key]['pass'] = [ # works like pdo, pass in the names and give them a value
'field' => strlen($row[$key]),
'required' => $brokenCondition[1]
];
} else {
$test[$key]['evaluate'] = 'field == required';
$test[$key]['pass'] = [
'field' => is_numeric($row[$key]),
'required' => true
];
}
}
}
}
echo '#----------------------------------------------------------------------------#';
# show test arr for reference
echo '<pre>';
print_r($test);
echo '</pre>';
# foreach test row, check against the condition
foreach ($test as $key => $item)
{
echo '<pre>';
var_dump($key. ': ' .$expressionLanguage->evaluate(
$item['evaluate'],
$item['pass']
));
echo '</pre>';
echo '+----------------------------------------------------------------------------+';
}
这现在通过ExpressionLanguage Symfony组件评估我自定义创建的php查询字符串。谢谢@deceze
参考:
https://symfony.com/doc/current/components/expression_language/syntax.html
https://symfony.com/doc/current/components/expression_language.html