CsvParser.php 2.8 KB
<?php
/**
 * Created by PhpStorm.
 * User: Cibermag
 * Date: 26.08.2015
 * Time: 17:00
 */

namespace backend\components;


use Yii;
use yii\base\ErrorException;
use common\components\debug\CustomVarDamp;

class CsvParser implements \IteratorAggregate {


    /** @var bool */
    private $hasHeaderRow;

    /** @var resource */
    private $file;

    /** @var out encoding charset */
    private $out_charset = 'UTF-8';
    /** @var out encoding charset */
    private $in_charset;
    /** @var int - first line for parsing */
    private $first_line;

    /** @var int - first column for parsing */
    private $first_column;

    /** @var array - array of headers values */
    private $keys;

    public function setup( $file, $first_line, $first_column, $hasHeaderRow = TRUE, $delimiter = ';')
    {

        $this->first_line = $first_line;
        $this->first_column = $first_column;

        $this->file = $file;

        $this->file->setCsvControl($delimiter);
        $this->file->setFlags(\SplFileObject::READ_CSV);
        $this->file->seek( $this->first_line );


        $this->in_charset = 'windows-1251';
        $this->hasHeaderRow = $hasHeaderRow;
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->read());
    }

    /**
     * @return array
     * @throws InvalidFileException
     * @deprecated Use ::read instead.
     */
    public function parseAll()
    {
        return $this->read();
    }

    /**
     * @return array
     * @throws InvalidFileException
     */
    public function read()
    {
        // @todo add comments
        $return = [];

        $line = 0;
        $this->keys = NULL;

        while (($row = $this->readRow()) !== FALSE) {
            $line++;

            if ($this->hasHeaderRow) {
                if ($this->keys === NULL) {
                    $this->keys = array_values($row);
                } else {

                    if (count($this->keys) !== count($row)) {
//
                        Yii::warning("Invalid columns detected on line #$line .");
                        return $return;
                    }

                    $return[] = array_combine($this->keys, $row);
                }
            } else {
                $return[] = $row;
            }
        }

        $this->closeHandler();

        return $return;
    }


    private function closeHandler()
    {
        $this->file = NULL;
    }

    private function readRow()
        // @todo add comments
    {
        $dirt_value_arr = $this->file->fgetcsv(  );
        $dirt_value_arr = array_slice( $dirt_value_arr, $this->first_column );
        $clear_arr = Encoder::encodeArray( $this->in_charset, $this->out_charset, $dirt_value_arr );

//        if ($this->keys !== NULL)
//            @$clear_arr[3] = ValueFilter::pricefilter($clear_arr[3]);

        return $clear_arr;

    }


}