diff --git a/README.md b/README.md index 7229d4f..b92e704 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ $ composer require backendtea/phinx-csv-seeder * PHP 5.6 or higher * robmorgan/phinx version 0.8.1 or higher +## Options +$truncate = true -- truncate table before insert +$ignoredField = ['...'] -- array with key name of csv to ignore + ## Usage Basic usage: diff --git a/src/CsvSeeder.php b/src/CsvSeeder.php index f94115b..69a1355 100644 --- a/src/CsvSeeder.php +++ b/src/CsvSeeder.php @@ -24,11 +24,30 @@ abstract class CsvSeeder extends AbstractSeed * @var string */ private $fileName; + + /** + * set variable truncate + */ + public $truncate = false; + + /** + * ignore csv field to insert + */ + public $ignoredField = []; public function insertCsv($table, $filename) { $this->fileName = $filename; $toInsert = $this->seedFromCSV(); + + if(true === $this->truncate) { + $table->truncate(); + } + + if(!empty($this->ignoredField)) { + $toInsert = $this->cleanIgnoredField($toInsert); + } + $this->insert($table, $toInsert); } @@ -103,7 +122,7 @@ private function isGzipped() * @param array $mapping * @return array */ - private function buildToInsertArray($csvRows, $mapping) + protected function buildToInsertArray($csvRows, $mapping) { $toBuild = []; $offset = 1 ; @@ -119,6 +138,20 @@ private function buildToInsertArray($csvRows, $mapping) } + /** + * remove field to insert + */ + private function cleanIgnoredField(array $fields): array + { + foreach($fields as $i => $row) { + foreach($row as $key => $_) { + if(in_array($key, $this->ignoredField)) { + unset($fields[$i][$key]); + } + } + } + return $fields; + }