caridea / filter
一个价值卫生库的小虾米
3.0.0
2018-01-20 20:54 UTC
Requires
- php: >=7.1.0
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^6.0.0
This package is not auto-updated.
Last update: 2024-09-14 20:03:57 UTC
README
Caridea 是一个微小的 PHP 应用程序库。当你只需要一些帮助而不需要一个完整的框架时,这个小虾米就是你所需要的。
这是它的价值卫生库。
安装
您可以使用 Composer 安装此库
$ composer require caridea/filter
- 此项目的 master 分支(版本 3.x)需要 PHP 7.1 和
mbstring
扩展。 - 此项目的 2.x 版本需要 PHP 7.0 和
mbstring
扩展。
合规性
此库的版本将符合 语义化版本控制。
我们的代码旨在遵守 PSR-1、PSR-2 和 PSR-4。如果您发现与标准合规性相关的问题,请发送一个 pull request!
文档
- 请访问 Read the Docs
示例
以下是一些简单的示例。让我们定义一组用于人员记录的过滤器。
// let's pretend this came from $_POST $input = [ 'name' => 'john smith ', 'birthday' => '1990-01-01__', 'bio' => "Mistakenly written on Windows\r\nThat's a problem. ", 'friends' => 'Jane' ]; $registry = new \Caridea\Filter\Registry(); // you can register your own filters if you choose $b = $registry->builder(); $b->always('name')->then('trim')->then('titlecase'); // always() will run chain even if missing from input $b->field('birthday')->then('regex', '/[^0-9-]/', ''); $b->field('bio')->then('trim')->then('nl'); // convert to UNIX newlines $b->always('species')->then('default', 'Homo sapiens'); $b->field('friends')->then('array')->each('trim'); // each() will run the filter on every element // by default, all fields you don't specify are dropped. // but! otherwise() can specify a fallback chain for any non-declared fields. // $b->otherwise('trim')->then('default', null); $filter = $b->build(); $output = $filter($input); var_dump($output);
array(5) {
'name' =>
string(10) "John Smith"
'birthday' =>
string(10) "1990-01-01"
'bio' =>
string(47) "Mistakenly written on Windows
That's a problem."
'species' =>
string(12) "Homo sapiens"
'friends' =>
array(1) {
[0] =>
string(4) "Jane"
}
}
您也可以提供一个或多个 Reducer
,这些 Reducer
用于一次性合并和重写多个值。
// let's pretend this came from $_POST $input = [ 'username' => ' doublecompile ', 'id-0' => '1', 'id-5' => '4', 'id-1' => '9' ]; $registry = new \Caridea\Filter\Registry(); $b = $registry->builder(); $b->always('username')->then('trim'); $b->reducer(Combiners::appender('ids', 'id-')); $filter = $b->build(); $output = $filter($input); var_dump($output);
array(2) {
'username' =>
string(13) "doublecompile"
'ids' =>
array(3) {
[0] =>
string(1) "1"
[1] =>
string(1) "4"
[2] =>
string(1) "9"
}
}
Filter
类本身就是一个 Reducer
。