diff --git a/backend/components/parsers/CsvParser.php b/backend/components/parsers/CsvParser.php index 7a5ab32..b024550 100644 --- a/backend/components/parsers/CsvParser.php +++ b/backend/components/parsers/CsvParser.php @@ -13,51 +13,71 @@ use Yii; use yii\base\ErrorException; use common\components\debug\CustomVarDamp; -class CsvParser implements \IteratorAggregate { +class CsvParser { /** @var bool */ - private $hasHeaderRow; + public $hasHeaderRow = false; /** @var resource */ - private $file; + public $file; /** @var out encoding charset */ - private $out_charset = 'UTF-8'; + public $out_charset = 'UTF-8'; /** @var out encoding charset */ - private $in_charset; + public $in_charset = 'windows-1251'; /** @var int - first line for parsing */ - private $first_line; + public $first_line = 0; /** @var int - first column for parsing */ - private $first_column; + public $first_column = 0; /** @var array - array of headers values */ - private $keys; + public $keys; + public $delimiter = ';'; + public $auto_detect_start_position = false; + public $min_column_quantity = 5; - public function setup( $file, $first_line, $first_column, $hasHeaderRow = false, $delimiter = ';') - { - - $this->first_line = $first_line; - $this->first_column = $first_column; - $this->file = $file; + public function setup() + { - $this->file->setCsvControl($delimiter); + if ($this->auto_detect_start_position) { + $this->first_line = $this->detectStartPosition(); + } + CustomVarDamp::dumpAndDie( $this->first_line ); + $this->file->setCsvControl($this->$delimiter); $this->file->setFlags(\SplFileObject::READ_CSV); $this->file->seek( $this->first_line ); - $this->in_charset = 'windows-1251'; - $this->hasHeaderRow = $hasHeaderRow; } - public function getIterator() + + + protected function detectStartPosition () { - return new \ArrayIterator($this->read()); - } + $first_column = 0; + $find = false; + while (!$find) { + + $j = 0; + $row = $this->readRow(); + $first_column++; + for ($i = 1; $i<=count($row); $i++) { + if (!$row[$i]) { + $j++; + } + if ( $j >= $this->min_column_quantity ) { + $find = true; + break; + } + } + } + return $first_column; + } /** * @return array diff --git a/backend/components/parsers/ParserHandler.php b/backend/components/parsers/ParserHandler.php index d244361..1cbea46 100644 --- a/backend/components/parsers/ParserHandler.php +++ b/backend/components/parsers/ParserHandler.php @@ -1,5 +1,6 @@ options->first_line )? $this->options->first_line : 0; $first_column = isset( $this->options->first_column )? $this->options->first_column : 0; + $csvParser = Yii::createObject([ + 'class' => 'backend\components\parsers\CsvParser', + 'file' => $this->fileObject, + ]); + //CustomVarDamp::dumpAndDie($csvParser); $csvParser = new CsvParser( ); $csvParser->setup( $this->fileObject, $first_line, $first_column ); -- libgit2 0.21.4