https://github.com/zumba/csv-policy
Simple, policy-driven csv rules validation
https://github.com/zumba/csv-policy
Last synced: 10 months ago
JSON representation
Simple, policy-driven csv rules validation
- Host: GitHub
- URL: https://github.com/zumba/csv-policy
- Owner: zumba
- Created: 2013-12-02T19:10:43.000Z (over 12 years ago)
- Default Branch: master
- Last Pushed: 2014-02-28T02:26:03.000Z (over 12 years ago)
- Last Synced: 2025-07-19T16:42:03.442Z (11 months ago)
- Language: PHP
- Homepage: http://engineering.zumba.com
- Size: 363 KB
- Stars: 8
- Watchers: 7
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# CsvPolicy
[](https://travis-ci.org/zumba/csv-policy)
**CsvPolicy** is a simple, policy-based validation library for CSV files. Create rules for columns in a CSV file and the validator will load them, parse the file, and report rule violations.
*CsvPolicy requires PHP >= 5.4*
## Example
Suppose you have the following business requirements for a CSV file named `products.csv` that will be uploaded to your application:
1. It must contain the following column names: `id`, `value`
2. It must contain at least one of the following columns: `upc`, `code`, `stock`
3. The `id` column's values must be unique.
4. The `value` column must only contain numeric values
CsvPolicy allows you to model these rules as classes. Required and optional fields are handled by the `Validator` class directly, so we only need to define rules for the `id` column and the `value` column.
CsvPolicy uses Traits for common validation operations (e.g. checking all values in a column are unique). The folowing rule will ensure that the values in the `id` field are unique:
```php
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;
}
}
```
You can override the `Rule::validationLogic` method to define custom validation for that column. The validator will use this method to check all of the values in the CSV for the column.
```php
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);
}
}
```
Finally, you configure your validator and use it to check if the CSV file is valid:
```php
$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();
}
```