hanneskod/clean
Composer 安装命令:
composer require hanneskod/clean
包简介
A clean (as in simple) data cleaner (as in validation tool)
README 文档
README
A clean (as in simple) data cleaner (as in validation tool)
Why?
Sometimes it's necessary to perform complex input validation, and a number of tools exist for this purpose (think Respect\Validation). At other times (arguably most times) built in php functions such as the ctype-family and regular expressions are simply good enough. At these times pulling in a heavy validation library to perform basic tasks can be unnecessarily complex.
Clean acts as a thin wrapper around callables and native php functions, in less than 100 logical lines of code, and allows you to filter and validate user input through a simple and compact fluent interface.
Installation
composer require hanneskod/clean
Clean requires php 7.4 or later and has no userland dependencies.
Usage
Basic usage consists of grouping a set of Rules in an ArrayValidator.
use hanneskod\clean\ArrayValidator; use hanneskod\clean\Rule; $validator = new ArrayValidator([ 'foo' => (new Rule)->match('ctype_digit'), 'bar' => (new Rule)->match('ctype_alpha'), ]); $tainted = [ 'foo' => 'not-valid only digits allowed', 'bar' => 'valid' ]; try { $validator->validate($tainted); } catch (Exception $e) { echo $e->getMessage(); }
Defining rules
Rules are defined using the pre(), match() and post() methods.
pre()takes any number ofcallablearguments to act as pre-match filters. Filters take an argument and return it in it's filtered state.post()takes any number ofcallablearguments to act as post-match filters. Filters take an argument and return it in it's filtered state.match()takes any number ofcallablearguments to act as validators. The callable should take an argument and return true if the argument is valid and false if it is not.
A rule definition might look like this:
use hanneskod\clean\Rule; $rule = (new Rule)->pre('trim')->match('ctype_alpha')->post('strtoupper'); // outputs FOOBAR echo $rule->validate(' foobar ');
Using the regexp matcher
The Rule validator comes with one special case matcher: regexp() to match
string input against a posix style regular expression (preg_match()).
use hanneskod\clean\Rule; $rule = (new Rule)->regexp('/A/'); // outputs ABC echo $rule->validate('ABC');
Making input optional
Rules may define a default value using the def() method. The default value is
used as a replacement for null. This effectively makes the field optional in
an ArrayValidator setting.
use hanneskod\clean\ArrayValidator; use hanneskod\clean\Rule; $validator = new ArrayValidator([ 'key' => (new Rule)->def('baz') ]); $data = $validator->validate([]); // outputs baz echo $data['key'];
Specifying custom exception messages
When validation fails an exception is thrown with a generic message describing
the error. Each rule may define a custom exception message using the msg()
method to fine tune this behaviour.
use hanneskod\clean\Rule; $rule = (new Rule)->msg('Expecting numerical input')->match('ctype_digit'); try { $rule->validate('foo'); } catch (Exception $e) { // outputs Expecting numerical input echo $e->getMessage(); }
Ignoring unknown input items
By default unkown intput items triggers exceptions.
use hanneskod\clean\ArrayValidator; $validator = new ArrayValidator([]); // throws a clean\Exception as key is not present in validator $validator->validate(['this-key-is-not-definied' => '']);
Use ignoreUnknown() to switch this functionality off.
use hanneskod\clean\ArrayValidator; $validator = (new ArrayValidator)->ignoreUnknown(); $clean = $validator->validate(['this-key-is-not-definied' => 'foobar']); // outputs empty echo empty($clean) ? 'empty' : 'not empty';
Nesting validators
ArrayValidators can be nested as follows:
use hanneskod\clean\ArrayValidator; use hanneskod\clean\Rule; $validator = new ArrayValidator([ 'nested' => new ArrayValidator([ 'foo' => new Rule ]) ]); $tainted = [ 'nested' => [ 'foo' => 'bar' ] ]; $clean = $validator->validate($tainted); //outputs bar echo $clean['nested']['foo'];
Inspecting validation results using applyTo()
The validate() method throws an exception as soon as a match fails. This may
of course not always be what you want. You can inspect the validation result
directly by using the applyTo() method instead.
use hanneskod\clean\Rule; $rule = (new Rule)->match('ctype_digit'); $result = $rule->applyTo('12345'); $result->isValid() == true; // outputs 12345 echo $result->getValidData();
Catching all of the failures
Individual errors can be accessed using the result object.
use hanneskod\clean\ArrayValidator; use hanneskod\clean\Rule; $validator = new ArrayValidator([ '1' => (new Rule)->match('ctype_digit')->msg('failure 1'), '2' => (new Rule)->match('ctype_digit')->msg('failure 2'), ]); // Both 1 and 2 will fail as they are not numerical $result = $validator->applyTo(['1' => '', '2' => '']); //outputs failure 1failure 2 foreach ($result->getErrors() as $errorMsg) { echo $errorMsg; }
Identifying a failing rule
use hanneskod\clean\ArrayValidator; use hanneskod\clean\Rule; $validator = new ArrayValidator([ 'foo' => (new Rule)->match('ctype_digit'), 'bar' => (new Rule)->match('ctype_digit'), ]); $result = $validator->applyTo([ 'foo' => 'not-valid', 'bar' => '12345' ]); // outputs foo echo implode(array_keys($result->getErrors()));
Implementing custom validators
use hanneskod\clean\AbstractValidator; use hanneskod\clean\Rule; use hanneskod\clean\ValidatorInterface; class NumberRule extends AbstractValidator { protected function create(): ValidatorInterface { return (new Rule)->match('ctype_digit'); } } // Outputs 1234 echo (new NumberRule)->validate('1234');
hanneskod/clean 适用场景与选型建议
hanneskod/clean 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.51k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2015 年 12 月 31 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「validator」 「validation」 「input validation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hanneskod/clean 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hanneskod/clean 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hanneskod/clean 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Yii2 map input widget. Allows you to select geographcal coordinates via a human-friendly inteface.
Widget to add a remaining character counter to text inputs and textareas
Runn Me! Validation and Sanitization Library
Extension for Opis JSON Schema
Native (browser) color input field for SilverStripe
Integration bundle for Aura.Input with Aura.Filter
统计信息
- 总下载量: 1.51k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 15
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: WTFPL
- 更新时间: 2015-12-31