csv-validator/example.php

55 lines
1.4 KiB
PHP
Raw Permalink Normal View History

2016-05-20 12:03:28 +02:00
<?php
use Deblan\Csv\CsvParser;
use Deblan\CsvValidator\Validator;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Date;
2016-05-22 19:17:47 +02:00
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
2016-05-20 12:03:28 +02:00
2016-05-22 19:17:47 +02:00
require __DIR__.'/vendor/autoload.php';
2016-05-20 12:03:28 +02:00
2016-05-22 19:17:47 +02:00
// Initialisation of the validator
2016-05-23 20:19:13 +02:00
$validator = new Validator();
2016-05-20 14:45:28 +02:00
2016-05-22 19:17:47 +02:00
// The first field must contain an email
2016-05-20 14:45:28 +02:00
$validator->addFieldConstraint(0, new Email());
2016-05-22 19:17:47 +02:00
// The second field must contain a date
2016-05-20 14:45:28 +02:00
$validator->addFieldConstraint(1, new Date());
2016-05-22 23:38:17 +02:00
// Validate the legend
$validator->setExpectedHeaders(['foo', 'bar', 'bim']);
2016-05-22 23:38:17 +02:00
2016-05-22 19:17:47 +02:00
// An line must contain 3 columns
2017-03-13 15:53:14 +01:00
$validator->addDataConstraint(new Callback(function ($data, ExecutionContextInterface $context) {
2016-05-22 19:17:47 +02:00
if (count($data) !== 6) { // 6 because of the legend (3 fields * 2)
$context->addViolation('The line must contain 3 columns');
}
}));
2016-05-23 20:19:13 +02:00
// Initialisation of the parser
$parser = new CsvParser();
$parser->setHasHeaders(true);
2016-05-23 20:19:13 +02:00
$validator->validate($parser->parseFile(__DIR__.'/tests/fixtures/example.csv'));
2016-05-20 12:03:28 +02:00
2016-05-20 14:45:28 +02:00
if ($validator->isValid() === false) {
2016-05-22 23:22:12 +02:00
foreach ($validator->getErrors() as $error) {
$line = $error->getLine();
2016-05-22 23:22:12 +02:00
$column = $error->getColumn();
$message = $error->getViolation()->getMessage();
2016-05-22 23:22:12 +02:00
echo <<<EOF
<ul>
<li>Line: $line</li>
<li>Column: $column</li>
<li>
<p>$message</p>
</li>
</ul>
EOF;
2016-05-20 14:45:28 +02:00
}
}