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
|
2017-03-12 19:22:52 +01:00
|
|
|
$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
|
2017-03-12 19:22:52 +01:00
|
|
|
$parser = new CsvParser();
|
|
|
|
$parser->setHasHeaders(true);
|
2016-05-23 20:19:13 +02:00
|
|
|
|
2017-03-12 19:22:52 +01: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) {
|
2017-03-12 19:22:52 +01:00
|
|
|
$line = $error->getLine();
|
2016-05-22 23:22:12 +02:00
|
|
|
$column = $error->getColumn();
|
|
|
|
$message = $error->getViolation()->getMessage();
|
2017-03-12 19:22:52 +01:00
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|