oshomo / csv-utils
一个CSV工具,用于读取、验证并将数据写入多种格式,包括JSON、XML等。
Requires
- php: >7.1.3
- ext-dom: *
- ext-json: *
- ext-mbstring: *
- ext-simplexml: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.19 || ^3.0
- phpunit/phpunit: ^5.7 || ^6.5 || ^7.0 || ^8.0
README
CSVUtils
确保在需要此包时使用标记版本。
目录
当前稳定版本
如何运行
我添加了一个示例index.php
文件,用于快速测试如何使用该包。要运行示例;从包根目录,运行composer install
,然后使用内置的php服务器运行php -S localhost:8000
,这将启动服务器在localhost:8000
。从浏览器访问URL,你应该在包根目录的sample
文件夹中看到生成的文件。
实现
Validator
期望一个有效的文件路径,CSV分隔符,一个验证规则数组,以及一个可选的消息数组以覆盖验证器的默认消息。
文档
初始化验证器
设置有效的csv文件路径,传递CSV分隔符,并传递您的验证规则。
use Oshomo\CsvUtils\Validator\Validator; $validator = new Validator( "some/valid/file_path", [ "name" => ["ascii_only"], "uri" => ["url"], "stars" => ["between:0,5"] ] );
验证CSV
现在我们准备验证CSV。验证器提供了一个validate
方法,可以像这样调用:$validator->validate();
。如果验证失败,validate
方法返回无效行的数组。如果验证通过,validate
方法返回CSV数据作为数组。
更好的实现
use Oshomo\CsvUtils\Validator\Validator; $validator = new Validator( "some/valid/file_path", [ 'title' => ["ascii_only", "url"] ] ); if ($validator->fails()) { // Do something when validation fails $errors = $validator->errors(); }
错误消息
要获取有验证错误的行及其错误,验证器公开一个errors
方法,可以像这样使用:$validator->errors()
。
您还可以通过将消息数组传递给验证器来自定义不同验证规则和不同属性的错误消息,如下所示
use Oshomo\CsvUtils\Validator\Validator; $validator = new Validator( "some/valid/file_path", ['title' => ["ascii_only", "url"]], [ 'ascii_only' => 'The :value supplied for :attribute attribute is invalid on line :line of the CSV.', // This specifies a custom message for a given attribute. 'hotel_link:url' => 'The :attribute must be a valid link. This error occured on line :line of the CSV.', ] );
在上面的示例中
:attribute
占位符将被验证的字段的实际名称替换。:value
占位符将替换正在验证的值。:line
占位符也将替换CSV中发生错误的行/行号。
您还可以在验证消息中使用其他占位符。例如,between
规则公开了两个其他占位符min
和max
。更多关于这一点,请参阅可用规则部分
可用规则
between:min,max
:
Validates that a cell value is between a :min and :max. The rule exposes the :min and :max placeholder for inline messages
ascii_only
:
Validates that a cell value does not contain a non-ascii character
url
:
Validates that a cell value is a valid URL. By valid URL we mean
(#protocol)
(#basic auth)
(#a domain name or #an IP address or #an IPv6 address)
(#a port(optional)) then
(#a /, nothing, a / with something, a query or a fragment)
写入CSV输出数据
CSV文件输出可以写入任何格式。当前支持的格式是xml
和json
。验证器公开一个write
方法,将输出数据写入与CSV相同的文件夹。下面是示例实现
use Oshomo\CsvUtils\Validator\Validator; use Oshomo\CsvUtils\Converter\JsonConverter; use Oshomo\CsvUtils\Converter\XmlConverter; $validator = new Validator( 'some/valid/file_path', [ "stars" => ["between:0,5"], "name" => ["ascii_only"], "uri" => ["url"], ] ); if(!$validator->fails()) { $validator->write(new JsonConverter()); $validator->write(new XmlConverter("hotel")); } else { print_r($validator->errors()); }
JsonConverter
简单地以JSON格式写入输出数据。XmlConverter
转换器以XML格式写入数据。XmlConverter
接受一个可选参数,用于设置XML记录元素。如果没有提供,则默认为item
。例如,$validator->write(new XmlConverter("hotel"));
将写入以下内容
<?xml version="1.0"?>
<data>
<hotel>
<name>Beni Gold Hotel and Apartments</name>
<stars>5</stars>
<uri>https://hotels.ng/hotel/86784-benigold-hotel-lagos</uri>
</hotel>
<hotel>
<name>Hotel Ibis Lagos Ikeja</name>
<stars>4</stars>
<uri>https://hotels.ng/hotel/52497-hotel-ibis-lagos-ikeja-lagos</uri>
</hotel>
</data>
注意:验证要么通过要么失败,您始终可以将CSV输出数据写入可用的格式。如果验证失败,写入的数据中会有额外的错误属性。
使用规则对象将自定义规则传递给验证器
将自定义规则传递给验证器很简单。创建一个实现Oshomo\CsvUtils\Contracts\ValidationRuleInterface
接口的CustomRule类。然后将其传递到规则数组中,很简单。例如
use Oshomo\CsvUtils\Validator\Validator; $validator = new Validator( 'some/valid/file_path', ["name" => ["ascii_only", new UppercaseRule]] );
UppercaseRule
的类定义。如果您想创建自己的规则,可以采用相同的方法。
use Oshomo\CsvUtils\Contracts\ValidationRuleInterface; class UppercaseRule implements ValidationRuleInterface { /** * Determines if the validation rule passes. This is where we do the * actual validation. If the validation passes return true else false * * @param mixed $value * @param $parameters * @return bool */ public function passes($value, array $parameters): bool { return strtoupper($value) === $value; } /** * Get the validation error message. Specify the message that should * be returned if the validation fails. You can make use of the * :attribute and :value placeholders in the message string * * @return string */ public function message(): string { return "The :attribute value :value must be uppercase on line :line."; } }
如果自定义规则接受像between
规则这样的参数,那么您的CustomRule类必须实现Oshomo\CsvUtils\Contracts\ValidationRuleInterface
和Oshomo\CsvUtils\Contracts\ParameterizedRuleInterface
。以Oshomo\CsvUtils\Rules\Between
为例。
使用闭包将自定义规则传递给验证器
如果您只需要在整个应用程序中使用自定义规则的特定功能一次,您可以使用闭包而不是规则对象。闭包接收属性的值,以及一个在验证失败时应该被调用的$fail
回调。
use Oshomo\CsvUtils\Validator\Validator; $validator = new Validator( "some/valid/file_path", [ "uri" => ["url", function($value, $fail) { if (strpos($value, "https://") !== 0) { return $fail('The URL passed must be https i.e it must start with https://'); } }] ]);
将CSV输出数据写入其他格式
将CSV输出数据写入其他格式也非常简单。创建一个实现Oshomo\CsvUtils\Contracts\ConverterHandlerInterface
接口的CustomConverter类。然后将其传递给验证器的write
方法,很简单。下面是一个JSON转换器的示例实现。
use Oshomo\CsvUtils\Contracts\ConverterHandlerInterface; class JsonConverter implements ConverterHandlerInterface { const FILE_EXTENSION = "json"; /** * The converted data * * @var string */ protected $data; /** * @return string */ public function getExtension(): string { return JsonConverter::FILE_EXTENSION; } /** * @param array $data * @return $this|mixed */ public function convert(array $data): ConverterHandlerInterface { $this->data = json_encode($data, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); return $this; } /** * @param string $filename * @return bool */ public function write(string $filename): bool { return (file_put_contents($filename, $this->data)) ? true : false; } } ////////////////////////////////////////////////////// // To use the converter above. ////////////////////////////////////////////////////// $validator->write(new JsonConverter());
运行测试
从包的根目录运行composer test
。
为此仓库做出贡献
请随意提交一个特性或错误修复的pull request。但是,请注意,在您的pull request可以合并之前,必须编写或更新测试用例。项目使用php-cs-fixer进行自动检查,以确保遵守Symfony代码标准。
因此,在推送或创建任何pull request之前,请运行以下命令
composer test
:用于运行测试composer fix-lint
:用于运行php-cs-fixer修复linting错误