php7 利用抽象语法树 AST 定义数据过滤和验证类 巧用__CALL

 话不多说 直接上代码 , 先定义Securityclass类 

namespace Application\Web;


class Securityclass
{
    public function __construct(){
        $this->filter=[
            'striptags'=>function($a){return strip_tags($a);},
            'digits'=>function($a){return preg_replace('/[^0-9]/','',$a);},
            'alpha'=>function($a){return preg_replace('/[^A-Z]/i','',$a);}
        ];
        $this->validate = [
            'alnum'=>function($a){return ctype_alnum($a);},
            'digits'=>function($s){return ctype_digit($s);},
            'alpha'=>function($a){return ctype_alpha($a);}
        ];
    }
// 使用preg_match 函数将$method 参数与单词filter和validate匹配,第二个子匹配操作的结果转化为对应的数组下标,如果都满足 则调用
public function __call($name, $arguments) { // TODO: Implement __call() method. preg_match('/^(filter|validate)(.*)$/i',$name,$matches); $prefix=$matches[1]??''; $function=strtolower($matches[2]??''); if ($prefix&&$function){ return $this->$prefix[$function]($arguments[0]); } return 'error'; } }

调用 

include '../Autoload/Loader.php';
\Application\Autoload\Loader::init(__DIR__.'/../..');
$security=new \Application\Web\Securityclass();
$data=[
    '<ul><li>Lots</li><li>OF</li><li>Tags</li></ul>'
    ,12345,
    'This is a string',
    'String with number 12345'
];
foreach ($data as $item){
    echo  'ORIGINAL: '.$item.PHP_EOL;
    echo  'FILTERING'.PHP_EOL;
    printf('%12s:%s'.PHP_EOL,'strip Tags',$security->filterStripTags($item));
    printf('%12s:%s'.PHP_EOL,'digits',$security->filterDigits($item));
    printf('%12s:%s'.PHP_EOL,'Alpha',$security->filterAlpha($item));

    echo  'VALIDATORS: '.PHP_EOL;
    printf('%12s:%s'.PHP_EOL,'Alpha',$security->filterAlpha($item));


}

输出 

FILTERING
  strip Tags:LotsOFTags
      digits:
       Alpha:ulliLotsliliOFliliTagsliul
VALIDATORS: 
       Alpha:ulliLotsliliOFliliTagsliul
ORIGINAL: 12345
FILTERING
  strip Tags:12345
      digits:12345
       Alpha:
VALIDATORS: 
       Alpha:
ORIGINAL: This is a string
FILTERING
  strip Tags:This is a string
      digits:
       Alpha:Thisisastring
VALIDATORS: 
       Alpha:Thisisastring
ORIGINAL: String with number 12345
FILTERING
  strip Tags:String with number 12345
      digits:12345
       Alpha:Stringwithnumber
VALIDATORS: 
       Alpha:Stringwithnumber

不要滥用这种处理方式,虽然这个基于ast很自由,如果是运行周期比较长的项目, 这里的代码会变的非常难理解, 上期维护是个问题, 慎重。

posted @ 2021-07-13 17:00  飘柔2019  阅读(110)  评论(0编辑  收藏  举报