CSV validator library.
Go to file
2016-05-22 19:18:38 +02:00
src/Deblan/CsvValidator Refactoring, tests 2016-05-22 18:37:12 +02:00
tests Documentation, tests 2016-05-22 19:17:47 +02:00
.gitignore init 2015-03-17 17:54:50 +01:00
composer.json First version 2016-05-20 12:01:26 +02:00
example.php Documentation, tests 2016-05-22 19:17:47 +02:00
LICENSE Init commit 2015-03-17 16:13:33 +01:00
phpunit.xml init 2015-03-17 17:54:50 +01:00
README.md Documentation 2016-05-22 19:18:38 +02:00

csv-validator

CSV validator library

That uses the constraints of Symfony framework: http://symfony.com/doc/current/reference/constraints.html.

Installation

You need composer:

composer require deblan/csv-validator dev-master

Example

<?php

use Deblan\Csv\CsvParser;
use Deblan\CsvValidator\Validator;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

require __DIR__.'/vendor/autoload.php';

// Initialisation of the parser
$parser = new CsvParser(__DIR__.'/tests/fixtures/example.csv');
$parser->setHasLegend(true);

// Initialisation of the validator
$validator = new Validator($parser, Validation::createValidator());

// The first field must contain an email
$validator->addFieldConstraint(0, new Email());

// The second field must contain a date
$validator->addFieldConstraint(1, new Date());

// An line must contain 3 columns
$validator->addDataConstraint(new Callback(function($data, ExecutionContextInterface $context) {
    if (count($data) !== 6) { // 6 because of the legend (3 fields * 2)
        $context->addViolation('The line must contain 3 columns');
    }
}));

$validator->validate();

if ($validator->isValid() === false) {
    foreach ($validator->getErrors() as $violation) {
        $line = $violation->getLine(); 
        $column = $violation->getColumn();
        $message = $violation->getViolation()->getMessage();
        
        // Up to you!
    }
}