truongwp / sanitizer
一个简单且独立的无依赖的净化库。
0.1.0
2017-05-30 22:38 UTC
Requires
- php: >= 5.3.0
Requires (Dev)
- php: >= 5.6
- phpunit/phpunit: ~5.7
This package is not auto-updated.
Last update: 2024-09-29 02:58:23 UTC
README
Sanitizer 是一个简单且独立的 PHP 净化库,无任何依赖。
安装
使用 Composer 进行安装和更新
composer require "truongwp/sanitizer=*"
Sanitizer 需要 PHP >= 5.3
使用方法
<?php $sanitizer = new Truongwp\Sanitizer\Sanitizer(); $input = array( 'name' => ' Foo bar ', 'age' => ' 24 ', ); $rules = array( 'name' => 'trim|strtolower|ucwords', 'age' => 'intval', ); $output = $sanitizer->sanitize($input, $rules);
输出结果 $output
array( 'name' => 'Foo Bar', 'age' => 24, );
可以通过 |
字符串分隔符传递多个规则,或者使用数组
<?php $rules = array( 'name' => array('trim', 'strtolower', 'ucwords'), 'age' => 'intval', );
默认情况下,规则名称是 PHP 函数。因此,您可以轻松添加自定义函数进行净化。
<?php function trim_slasses($value) { return trim($value, '/'); } $sanitizer = new Truongwp\Sanitizer\Sanitizer(); $input = array( 'name' => '//foo', ); $rules = array( 'name' => 'trim_slasses', ); $output = $sanitizer->sanitize($input, $rules);
结果
array( 'name' => 'foo', )
如果您想将额外的参数传递给净化函数,可以将它们附加到规则名称上,并通过 :
分隔。
<?php function prefix_suffix($value, $prefix = '', $suffix = '') { return $prefix . $value . $suffix; } $sanitizer = new Truongwp\Sanitizer\Sanitizer(); $input = array( 'name' => 'foo', ); $rules = array( 'name' => 'prefix_suffix:prefix_:_suffix', ); $output = $sanitizer->sanitize($input, $rules);
结果
array( 'name' => 'prefix_foo_suffix', )
您还可以通过使用 SanitizerRegistry 添加自定义净化类。
<?php class DateFormatSanitizer implements Truongwp\Sanitizer\Contracts\RuleSanitizer { /** * Sanitize value. * * @param mixed $value Value need to sanitize. * @return mixed */ public function sanitize($value) { $args = func_get_args(); $format = empty($args[1]) ? 'Y-m-d' : $args[1]; $timestamp = strtotime($value); return date($format, $timestamp); } } // Register rule sanitizers. Truongwp\Sanitizer\Registries\SanitizerRegistry::set('date_format', new DateFormatSanitizer()); $sanitizer = new Truongwp\Sanitizer\Sanitizer(); $input = array( 'day' => '05/30/2017', ); $rules = array( 'name' => 'date_format:Y-m-d', ); $output = $sanitizer->sanitize($input, $rules);
结果
array( 'day' => '2017-05-30', )
贡献
贡献者: @truongwp
欢迎提交错误报告或拉取请求。