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.4KB

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