CSV validator library.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

example.php 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. use Deblan\Csv\CsvParser;
  3. use Deblan\CsvValidator\Validator;
  4. use Symfony\Component\Validator\Validation;
  5. use Symfony\Component\Validator\Constraints\Email;
  6. use Symfony\Component\Validator\Constraints\Date;
  7. use Symfony\Component\Validator\Constraints\Callback;
  8. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  9. require __DIR__.'/vendor/autoload.php';
  10. // Initialisation of the validator
  11. $validator = new Validator();
  12. // The first field must contain an email
  13. $validator->addFieldConstraint(0, new Email());
  14. // The second field must contain a date
  15. $validator->addFieldConstraint(1, new Date());
  16. // Validate the legend
  17. $validator->setExpectedHeaders(['foo', 'bar', 'bim']);
  18. // An line must contain 3 columns
  19. $validator->addDataConstraint(new Callback(function($data, ExecutionContextInterface $context) {
  20. if (count($data) !== 6) { // 6 because of the legend (3 fields * 2)
  21. $context->addViolation('The line must contain 3 columns');
  22. }
  23. }));
  24. // Initialisation of the parser
  25. $parser = new CsvParser();
  26. $parser->setHasHeaders(true);
  27. $validator->validate($parser->parseFile(__DIR__.'/tests/fixtures/example.csv'));
  28. if ($validator->isValid() === false) {
  29. foreach ($validator->getErrors() as $error) {
  30. $line = $error->getLine();
  31. $column = $error->getColumn();
  32. $message = $error->getViolation()->getMessage();
  33. echo <<<EOF
  34. <ul>
  35. <li>Line: $line</li>
  36. <li>Column: $column</li>
  37. <li>
  38. <p>$message</p>
  39. </li>
  40. </ul>
  41. EOF;
  42. }
  43. }