Skip to content

Commit

Permalink
Added required headings as optional array to the maker
Browse files Browse the repository at this point in the history
  • Loading branch information
stefandanaita committed Jan 26, 2017
1 parent 6ab0671 commit f3fa633
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/CsvValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class CsvValidator
$rules = [],
$headingKeys = [],
$errors = [],
$requiredHeadings = [],
$trim = true,
$encoding = 'UTF-8';

Expand All @@ -22,8 +23,9 @@ class CsvValidator
* @param string $encoding
* @return $this
*/
public function make(\SplFileObject $csv, $rules, $trim = true, $encoding = 'UTF-8')
public function make(\SplFileObject $csv, $rules, $requiredHeadings = [], $trim = true, $encoding = 'UTF-8')
{
$this->setRequiredHeadings($requiredHeadings);
$this->setTrim($trim);
$this->setEncoding($encoding);
$this->setCSV($csv);
Expand Down Expand Up @@ -102,12 +104,22 @@ protected function validateHeadingRow($row)
{
$errors = [];

// Check if the existing headings are valid
foreach ($row as $index => $heading) {
if (!in_array($heading, $this->getHeadingKeys())) {
$errors[$heading][0] = 'Heading ' . $heading . ' is not a valid heading for this CSV.';
}
}

// Check if all the required headings are present
if(!empty($this->getRequiredHeadings()) && $this->getRequiredHeadings() !== array_intersect($this->getRequiredHeadings(), $row)) {
foreach($this->getRequiredHeadings() as $index => $heading) {
if(!in_array($heading, $row)) {
$errors[$heading][0] = 'Heading ' . $heading . ' is missing from the CSV.';
}
}
}

if(!empty($errors)) {
$this->setErrors(0, $errors);
}
Expand Down Expand Up @@ -244,6 +256,23 @@ protected function combineRowHeader($row, $headingRow)
return $combined;
}

/**
* @param $headings
* @return void
*/
private function setRequiredHeadings($headings)
{
$this->requiredHeadings = $headings;
}

/**
* @return array
*/
public function getRequiredHeadings()
{
return $this->requiredHeadings;
}

/**
* @param $content
* @return string
Expand Down

0 comments on commit f3fa633

Please sign in to comment.