ParserHandler.php 1.61 KB
<?php
namespace backend\components\parsers;
use common\components\debug\CustomVarDamp;

use Yii;


class ParserHandler {

/** @var string */
    private $filePath;

    /** @var instance of SplFileObject */
    private $fileObject;

    /** @var string - extension of file $filePath */
    private $extension;

    /** @var string - extension of file $filePath */
    private $options;

    /**
     * @param string first line in file for parsing
     */
    public function __construct( $filePath, $options  )
    {
        $this->filePath = $filePath;
        $this->options = $options;

        try {
            $this->fileObject = new \SplFileObject( $this->filePath , 'r' );;
        } catch (\ErrorException $e) {
            Yii::warning("Ошибка открытия файла {$this->filePath}");
        }

        //preg_match( '/\.[^\.]+$/i',$filePath, $resultArray );
        $this->extension = $this->fileObject->getExtension();
        $this->run();
    }

    public function run(){
        if ($this->extension = 'csv'){
            $first_line = isset( $this->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 );

            return $csvParser->read();
        };
    }
}