zumba / csv-policy
简单,基于策略的CSV规则验证
v0.2.0
2014-01-02 21:36 UTC
Requires
- php: >=5.4
- doctrine/inflector: ~1.0
This package is auto-updated.
Last update: 2024-08-24 04:04:11 UTC
README
CsvPolicy 是一个简单的基于策略的CSV文件验证库。为CSV文件中的列创建规则,验证器将加载它们,解析文件,并报告规则违规。
CsvPolicy 需要 PHP >= 5.4
示例
假设你有一个名为 products.csv
的CSV文件,该文件将被上传到你的应用程序,并且有以下业务需求
- 它必须包含以下列名:
id
,value
- 它必须包含以下列中的至少一个:
upc
,code
,stock
id
列的值必须是唯一的。value
列只能包含数字值
CsvPolicy 允许你将规则建模为类。必填字段和可选字段由 Validator
类直接处理,因此我们只需要定义 id
列和 value
列的规则。
CsvPolicy 使用 Traits 来实现常见的验证操作(例如,检查列中的所有值是否唯一)。以下规则将确保 id
字段中的值是唯一的
namespace Zumba\CsvPolicy\Rule\Products; use \Zumba\CsvPolicy\Behavior; class Id extends \Zumba\CsvPolicy\Rule { use Unique; public function getErrorMessage($input) { return 'Id must be unique. Duplicate found: ' . $input; } }
你可以覆盖 Rule::validationLogic
方法来定义该列的自定义验证。验证器将使用此方法来检查CSV中该列的所有值。
namespace Zumba\CsvPolicy\Rule\Products; class Value extends \Zumba\CsvPolicy\Rule { public function getErrorMessage($input) { return 'Value must only contain numeric values. Non-numeric value found: ' . $input; } public function validationLogic($input) { return is_numeric($input); } }
最后,你配置你的验证器并使用它来检查CSV文件是否有效
$validator = new \Zumba\CsvPolicy\Validator(); $validator->config([ 'rulesPath' => './path/to/custom/rules' 'requiredFields' => [ // string field names are always required 'id', 'value', // arrays of field names indicate that at least one field is required, but not all ['upc', 'code', 'stock'] ] ]); $valid = $validator->isValid('./path/to/products.csv'); if (!$valid){ // errors is an array of rules violations $errors = $validator->getErrors(); }