diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index cfcce21..7854d4f 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -15,6 +15,7 @@ use backend\models\Importers; use yii\base\ErrorException; use common\components\PriceWriter; use common\components\CustomVarDamp; +use common\components\CustomArrayHelper; /** * Parser controller @@ -54,7 +55,6 @@ class ParserController extends BaseController $model = new UploadFileParsingForm(); // установим режим, 0 - ручная загрузка, 1 - автозагрузка $model->mode = $mode; - //CustomVarDamp::dumpAndDie(phpinfo()); return $this->render('index', ['model' => $model]); } @@ -186,7 +186,7 @@ class ParserController extends BaseController // соотнесем отпарсенные данные с соответсивем полученным от пользователя // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию - $data = \Yii::$app->multiparser->convertToAssocArray($data, $arr , 'attr_'); + $data = CustomArrayHelper::createAssocArray( $data, $arr , 'attr_' ); // запустим специальный класс который запишет данные в таблицы связанные с прайсами $writer = new PriceWriter(); diff --git a/backend/models/UploadFileParsingForm.php b/backend/models/UploadFileParsingForm.php index c66ab5e..165d7a1 100644 --- a/backend/models/UploadFileParsingForm.php +++ b/backend/models/UploadFileParsingForm.php @@ -75,8 +75,8 @@ class UploadFileParsingForm extends Model throw new ErrorException("Ошибка чтения из файла прайса {$this->file_path}"); } // файл больше не нужен - данные прочитаны и сохранены в кеш - if( file_exists($this->file_path) ) - unlink($this->file_path); +// if( file_exists($this->file_path) ) +// unlink($this->file_path); return $data; } diff --git a/common/components/CustomArrayHelper.php b/common/components/CustomArrayHelper.php new file mode 100644 index 0000000..bd76aa6 --- /dev/null +++ b/common/components/CustomArrayHelper.php @@ -0,0 +1,75 @@ + $sub_value) { + if (isset($key_array[$sub_key])) { + // если такой ключ в базовом массиве (массиве ключей) есть, то заменим новым, иначе просто удалим + $new_key = $key_array[$sub_key]; + if (!array_key_exists($new_key, $res)) { + $res[$new_key] = $value[$sub_key]; + } + } + unset($res[$sub_key]); + $value = $res; + } + + }, + $key_array); + + return $value_arr; + } + + /** + * @param $value_arr - двумерный массив к которому нужно добавить колонки + * @param $add_array - массив с колонками (ключи) и значениями колонок + * @return mixed + */ + public static function addColumns(array $value_arr, array $add_array) + { + $i = 0; + while ($i < count($value_arr)) { + foreach ($add_array as $add_key => $add_value) { + $value_arr[$i][$add_key] = $add_value; + } + $i++; + } + return $value_arr; + } +} \ No newline at end of file diff --git a/common/components/PriceWriter.php b/common/components/PriceWriter.php index ecc88ff..d6b27a5 100644 --- a/common/components/PriceWriter.php +++ b/common/components/PriceWriter.php @@ -62,20 +62,20 @@ class PriceWriter // преобразуем числовые значения foreach ($this->data as &$row) { - $row['PRICE'] = \Yii::$app->multiparser->convertToFloat($row['PRICE']); - $row['BOX'] = \Yii::$app->multiparser->convertToInteger($row['BOX']); + $row['PRICE'] = \Yii::$app->converter->convertTo('float',$row['PRICE']); + $row['BOX'] = \Yii::$app->converter->convertTo('integer',$row['BOX']); // присвоим полный артикул $row['FULL_ARTICLE'] = $row['ARTICLE']; if ((int)$this->configuration['delete_prefix']) { - $row = \Yii::$app->multiparser->convertToArticle( $row, $this->configuration['importer_id'] ); + $row = \Yii::$app->converter->convertTo( 'Article', $row, ['importer_id' => $this->configuration['importer_id']] ); } else { - $row['ARTICLE'] = \Yii::$app->multiparser->convertToArticle( $row['ARTICLE'] ); + $row['ARTICLE'] = \Yii::$app->converter->convertTo( 'Article', $row['ARTICLE'] ); } if (isset($row['ADD_BOX'])) - $row['ADD_BOX'] = \Yii::$app->multiparser->convertToInteger($row['ADD_BOX']); + $row['ADD_BOX'] = \Yii::$app->converter->convertTo( 'integer', $row['ADD_BOX'] ); // проверим все ли обязательные колонки были указаны пользователем $details_model->load(['Details' => $row]); @@ -87,7 +87,7 @@ class PriceWriter } // дополним данные значением импортера и даты обновления цены - $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]); + $this->data = CustomArrayHelper::addColumns( $this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date] ); try { //@todo add transaction diff --git a/common/components/parsers/CustomConverter.php b/common/components/parsers/CustomConverter.php index e233f87..7907fe1 100644 --- a/common/components/parsers/CustomConverter.php +++ b/common/components/parsers/CustomConverter.php @@ -10,71 +10,11 @@ use backend\models\ImportersPrefix; class CustomConverter extends Converter { - /** - * @param $value_arr - двумерный массив значений, которому нужно присвоить ключи - * @param $key_array - ключи для вложенного массива - * @return array - таблица с проименованными колонками - */ public static $sign; public static $multiplier; public static $importer_id; public static $brand; - public static function convertToAssocArray(array $value_arr, array $key_array, $key_prefix = '') - { - // очистка служебного префикса в массиве заголовков - if ($key_prefix) { - // @todo оптимизировать - два переворота массива - избыточно - $key_array = array_flip($key_array); - - array_walk($key_array, function (&$value, $key, $key_prefix) { - $value = str_replace($key_prefix, '', $value); - }, $key_prefix); - - $key_array = array_flip($key_array); - //уберем пустые элементы - $key_array = array_filter($key_array, function ($value) { - return $value !== ''; - }); - } - - array_walk($value_arr, - function (&$value, $key, $key_array) { - $res = $value; - foreach ($res as $sub_key => $sub_value) { - if (isset($key_array[$sub_key])) { - // если такой ключ в базовом массиве (массиве ключей) есть, то заменим новым, иначе просто удалим - $new_key = $key_array[$sub_key]; - if (!array_key_exists($new_key, $res)) { - $res[$new_key] = $value[$sub_key]; - } - } - unset($res[$sub_key]); - $value = $res; - } - - }, - $key_array); - - return $value_arr; - } - - /** - * @param $value_arr - двумерный массив к которому нужно добавить колонки - * @param $add_array - массив с колонками (ключи) и значениями колонок - * @return mixed - */ - public function addColumns(array $value_arr, array $add_array) - { - $i = 0; - while ($i < count($value_arr)) { - foreach ($add_array as $add_key => $add_value) { - $value_arr[$i][$add_key] = $add_value; - } - $i++; - } - return $value_arr; - } public static function convertToDetails(array $row) { @@ -143,11 +83,8 @@ class CustomConverter extends Converter } - public static function convertToArticle( $value, $importer_id = '' ) + public static function convertToArticle( $value ) { - if(isset( $importer_id )){ - self::$importer_id = $importer_id; - } if (is_array($value)) { @@ -189,7 +126,7 @@ class CustomConverter extends Converter public static function convertToBrand($value) { - $res = parent::convertToEncode($value);; + $res = self::convertToEncode($value);; $res = trim(strtoupper($res)); $res = str_replace("Ä", "A", str_replace("Ö", "O", str_replace("Ü", "U", str_replace("Ë", "E", str_replace("Ò", "O", $res))))); $res = str_replace(array('@', '#', '~', '"', "'", "?", "!"), '', $res); @@ -197,12 +134,5 @@ class CustomConverter extends Converter return $res; } - public static function convertToString($value) - { - $value = parent::convertToEncode($value); - - return str_replace(array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '=', '-', '~', '`', '"', "'", ' ', '№', '%', ';', ':', '[', ']', '{', '}', '*', '?', '/', '\'', '|', '.', ',', '<', '>', '\\'), '', $value); - } - } \ No newline at end of file diff --git a/common/components/parsers/CustomCsvParser.php b/common/components/parsers/CustomCsvParser.php index ed92588..b21fbca 100644 --- a/common/components/parsers/CustomCsvParser.php +++ b/common/components/parsers/CustomCsvParser.php @@ -19,31 +19,19 @@ class CustomCsvParser extends \yii\multiparser\CsvParser { public $last_line = 100; //public $hasHeaderRow = true; // public $keys = ['first','second', 'third', 'forth', 'fifth']; - public function setupConverter() - { - if (!count($this->converter_conf)) { - if ($this->hasHeaderRow) { - // если у файла есть заголовок, то в результате имеем ассоциативный массив - $this->converter_conf['hasKey'] = 1; - - } - - } -// $this->converter = \Yii::createObject( $this->converter_conf ); -// CustomVarDamp::dumpAndDie($this->converter); - } - - /** - * @param $arr - * @return mixed - * преобразовует значения прочитанного массива в нужные типы, согласно конфигурации конвертера - */ - protected function convert($arr) - { - $arr = \Yii::$app->multiparser->convertByConfiguration( $arr, $this->converter_conf ); - - return $arr; - - } +// public function setupConverter() +// { +// if (!count($this->converter_conf)) { +// if ($this->hasHeaderRow) { +// // если у файла есть заголовок, то в результате имеем ассоциативный массив +// $this->converter_conf['hasKey'] = 1; +// +// } +// +// } +//// $this->converter = \Yii::createObject( $this->converter_conf ); +// } + + } \ No newline at end of file diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index 0d74c94..8f2382f 100644 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -5,7 +5,7 @@ ['class' => 'common\components\parsers\CustomCsvParser', 'auto_detect_first_line' => true, 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', // @todo переделать на компонент + 'class' => 'common\components\parsers\CustomConverter', 'configuration' => ["encode" => 'DESCR'],] ], 'console' => @@ -13,7 +13,7 @@ 'auto_detect_first_line' => true, 'hasHeaderRow' => true, 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', + 'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => ["string" => 'DESCR', "float" => 'PRICE', @@ -42,7 +42,7 @@ 'hasHeaderRow' => true, 'keys' =>['ARTICLE', 'CROSS_ARTICLE', 'BRAND', 'CROSS_BRAND'], 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', + 'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => [ "brand" => ['BRAND', 'CROSS_BRAND'], @@ -55,7 +55,7 @@ ['class' => 'yii\multiparser\XmlParser', 'node' => 'Товар', 'converter_conf' => [ - //'class' => ' common\components\parsers\CustomConverter', + 'class' => ' common\components\parsers\CustomConverter', 'hasKey' => 1, 'configuration' => ["details" => [] ],], diff --git a/common/config/main.php b/common/config/main.php index 42035f7..c4e33b0 100644 --- a/common/config/main.php +++ b/common/config/main.php @@ -15,14 +15,15 @@ return [ ] ], 'multiparser'=>[ - 'class' => 'yii\multiparser\YiiMultiparser', 'configuration' => $mp_configuration, - 'as behavior' => [ - 'class' => 'common\components\parsers\CustomConverter', + ], + 'converter'=>[ + 'class' => 'yii\multiparser\YiiConverter', + 'configuration' => [ + 'class' => 'common\components\parsers\CustomConverter' + ], ], ], - ], - ]; diff --git a/common/models/DetailsCurrency.php b/common/models/DetailsCurrency.php index 4a7960a..87ab9fa 100644 --- a/common/models/DetailsCurrency.php +++ b/common/models/DetailsCurrency.php @@ -6,7 +6,7 @@ use Yii; /** * This is the model class for table "{{%details_currency}}". - * + * w_details_currency - СПЕЦИАЛЬНО СОЗАДННАЯ ВЬЮШКА ДЛЯ ДОСТУПА К СПИСКУ ТОВАРОВ С ВАЛЮТАМИ И ИХ КУРСАМИ * @property string $ID * @property string $IMPORT_ID * @property string $BRAND diff --git a/vendor/yiisoft/multiparser/Converter.php b/vendor/yiisoft/multiparser/Converter.php index dd5ae42..6865c55 100644 --- a/vendor/yiisoft/multiparser/Converter.php +++ b/vendor/yiisoft/multiparser/Converter.php @@ -1,18 +1,15 @@ ', '\\'), '', $value); + } /** * @param $name - имя метода конвертации * @param $value - значение на конвертацию * @return mixed */ - public static function __callStatic( $name, $value ) + public static function __callStatic($name, $value) { - $method_name = self::METHOD_PREFIX . $name; + $method_name = self::METHOD_PREFIX . $name; - if ( method_exists( static::class, $method_name ) ) { - return static::$method_name( $value[0] ); + if (method_exists(static::class, $method_name)) { + return static::$method_name($value[0]); - } else{ + } else { // если такого метода конвертации не предусмотрено, то возвращаем не конвертируя return $value[0]; @@ -87,7 +90,7 @@ class Converter extends Behavior public function __call($name, $params) { - return self::__callStatic( $name, $params ); + return self::__callStatic($name, $params); } @@ -97,39 +100,36 @@ class Converter extends Behavior * @return mixed * конвертирует массив по полученным настройкам, вызывая последовательно функции конвертации (указанные в конфигурации) */ - public static function convertByConfiguration( $arr, $configuration ) + public static function convertByConfiguration($arr, $configuration) { - if( $hasKey = isset( $configuration['hasKey'] ) ) - unset( $configuration['hasKey'] ); + if ($hasKey = isset($configuration['hasKey'])) + unset($configuration['hasKey']); - if ( isset( $configuration['configuration'] ) ) { + if (isset($configuration['configuration'])) { $arr_config = $configuration['configuration']; - unset( $configuration['configuration'] ); - } else{ - throw new ErrorException('Не указан обязательный параметр конфигурационного файла - converter_conf[configuration]'); + unset($configuration['configuration']); + } else { + throw new \ErrorException('Не указан обязательный параметр конфигурационного файла - converter_conf[configuration]'); } - // проставим аттрибуды из конфига{}{} - foreach ($configuration as $key_setting => $setting) { - if( property_exists( static::class, $key_setting ) ) - static::$$key_setting = $setting; - } + // проставим аттрибуты из конфига{}{} + self::setAttributes($configuration); - foreach ( $arr_config as $key => $value ) { - if ( $hasKey ){ + foreach ($arr_config as $key => $value) { + if ($hasKey) { // у нас ассоциативный массив, и мы можем конвертировать каждое значение в отдельности - if ( is_array( $value ) ) { + if (is_array($value)) { //если пустой массив то конвертируем всю строку - if (count( $value ) === 0 ){ + if (count($value) === 0) { - $arr = self::$key( $arr ); + $arr = self::$key($arr); continue; } // иначе конвертируем каждую ячейку в отдельности foreach ($value as $sub_value) { if (isset($arr[$sub_value])) { // конвертируем только те ячейки которые сопоставлены в прочитанном массиве с колонками в конфигурационном файле - $arr[$sub_value] = self::$key( $arr[$sub_value] ); + $arr[$sub_value] = self::$key($arr[$sub_value]); } } @@ -137,15 +137,15 @@ class Converter extends Behavior if (isset($arr[$value])) { // конвертируем только те ячейки которые сопоставлены в прочитанном массиве с колонками в конфигурационном файле - $arr[$value] = self::$key( $arr[$value] ); - // CustomVarDamp::dump($result); + $arr[$value] = self::$key($arr[$value]); + // CustomVarDamp::dump($result); } } } else { // нет заголовка - мы можем конвертировать только строку в целом - $arr = self::$key( $arr ); + $arr = self::$key($arr); } } @@ -153,6 +153,14 @@ class Converter extends Behavior return $arr; } + public static function setAttributes($configuration) + { + foreach ($configuration as $key_setting => $setting) { + if (property_exists(static::class, $key_setting)) + static::$$key_setting = $setting; + } + + } } \ No newline at end of file diff --git a/vendor/yiisoft/multiparser/ConverterInterface.php b/vendor/yiisoft/multiparser/ConverterInterface.php new file mode 100644 index 0000000..2fb22b8 --- /dev/null +++ b/vendor/yiisoft/multiparser/ConverterInterface.php @@ -0,0 +1,16 @@ +auto_detect_first_line) { $this->shiftToFirstValuableLine(); } - $this->setupConverter(); - - } - - /** - * устанавливает конвертер значений согласно конфигурационным настройкам - */ - public function setupConverter() - { - if (!count($this->converter_conf)) { - $this->converter = new Converter(); - if ($this->hasHeaderRow) { - // если у файла есть заголовок, то в результате имеем ассоциативный массив - $this->converter_conf['hasKey'] = 1; - } - //$this->converter->configuration = $this->converter_conf; + if ($this->hasHeaderRow) { + // если у файла есть заголовок, то в результате имеем ассоциативный массив + $this->converter_conf['hasKey'] = 1; } - } + parent::setup(); + } /** * определяет первую значимую строку, * считывается файл пока в нем не встретится строка с непустыми колонками @@ -208,25 +195,5 @@ class CsvParser implements ParserInterface } - /** - * @param $arr - * @return mixed - * преобразовует значения прочитанного массива в нужные типы, согласно конфигурации конвертера - */ - protected function convert($arr) - { - $result = $arr; - $converter = $this->converter; - - if (!is_null($converter)) { - - $result = $converter->convertByConfiguration( $arr, $this->converter_conf ); - - } - - return $result; - - } - } \ No newline at end of file diff --git a/vendor/yiisoft/multiparser/ObjectCreator.php b/vendor/yiisoft/multiparser/ObjectCreator.php new file mode 100644 index 0000000..c00d7de --- /dev/null +++ b/vendor/yiisoft/multiparser/ObjectCreator.php @@ -0,0 +1,30 @@ + $value) { + $object->$name = $value; + } + + return $object; + } +} \ No newline at end of file diff --git a/vendor/yiisoft/multiparser/Parser.php b/vendor/yiisoft/multiparser/Parser.php new file mode 100644 index 0000000..bba4a7f --- /dev/null +++ b/vendor/yiisoft/multiparser/Parser.php @@ -0,0 +1,51 @@ +setupConverter(); + } + + protected function setupConverter() + { + $converter = ObjectCreator::build( $this->converter_conf ); + if ( $converter instanceof ConverterInterface ) { + + $this->converter = $converter; + + } + + } + + public abstract function read(); + + /** + * @param $arr + * @return mixed + * преобразовует значения прочитанного массива в нужные типы, согласно конфигурации конвертера + */ + protected function convert( $arr ) + { + if ($this->converter !== NULL) { + + $arr = $this->converter->convertByConfiguration( $arr, $this->converter_conf ); + + } + + + return $arr; + + } +} \ No newline at end of file diff --git a/vendor/yiisoft/multiparser/ParserConfigurator.php b/vendor/yiisoft/multiparser/ParserConfigurator.php deleted file mode 100644 index 2e54d78..0000000 --- a/vendor/yiisoft/multiparser/ParserConfigurator.php +++ /dev/null @@ -1,32 +0,0 @@ -filePath = $filePath; if (isset($options['mode'])) { @@ -45,36 +49,22 @@ class ParserHandler $this->options = $options; - try { - $this->fileObject = new \SplFileObject($this->filePath, 'r'); - } catch (\ErrorException $e) { - // Yii::warning("Ошибка открытия файла {$this->filePath}"); - echo "Ошибка открытия файла {$this->filePath}"; - return []; - } + $this->fileObject = new \SplFileObject($this->filePath, 'r'); $options['file'] = $this->fileObject; $this->extension = $this->fileObject->getExtension(); - try { - $this->configuration = ParserConfigurator::getConfiguration($this->extension, $this->mode); - $this->configuration = array_merge($this->configuration, $options); - - } catch (\ErrorException $e) { - echo $e->getMessage(); - return []; - } + $this->custom_configuration = $this->getCustomConfiguration($this->extension, $this->mode); + $this->custom_configuration = array_merge_recursive($this->custom_configuration, $options); } public function run() { - $result = []; - // @todo - rewrite to universal manner - // \common\components\CustomVarDamp::dumpAndDie($this); - if (count($this->configuration)) { - $parser = Yii::createObject($this->configuration); + if (count($this->custom_configuration)) { + + $parser = $this->createObjectByConfiguration($this->custom_configuration); try { @@ -91,5 +81,32 @@ class ParserHandler return $result; } + + public function getCustomConfiguration($extension, $parameter) + { + if (!count($this->configuration)) { + $this->setConfiguration(require(__DIR__ . '/config.php')); + } + + if (!isset($this->configuration[$extension])) { + throw new \ErrorException("Parser do not maintain file with extension {$extension}"); + } + if (!isset($this->configuration[$extension][$parameter])) { + throw new \ErrorException("Parser configurator do not have settings for {$parameter} parameter"); + } + + return $this->configuration[$extension][$parameter]; + } + + public function setConfiguration($configuration) + { + $this->configuration = $configuration; + } + + protected function createObjectByConfiguration($configuration) + { + return ObjectCreator::build($configuration); + } } + diff --git a/vendor/yiisoft/multiparser/ParserInterface.php b/vendor/yiisoft/multiparser/ParserInterface.php deleted file mode 100644 index 1cdeb0f..0000000 --- a/vendor/yiisoft/multiparser/ParserInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -configuration ); + if ( $converter instanceof ConverterInterface ) { + + $this->converter = $converter; + }else{ + throw new ErrorException('Wrong type of converter'); + } + + + } + + public function convertTo( $method, $value, $attributes = [] ){ + + if ( $attributes ) { + $this->converter->setAttributes($attributes); + } + return $this->converter->$method( $value ); + + } + + public function convertByConfiguration( $value, $configuration ){ + + return $this->converter->convertByConfiguration( $value, $configuration ); + + } + + +} \ No newline at end of file diff --git a/vendor/yiisoft/multiparser/YiiMultiparser.php b/vendor/yiisoft/multiparser/YiiMultiparser.php index 58ff2d7..18fdbb5 100644 --- a/vendor/yiisoft/multiparser/YiiMultiparser.php +++ b/vendor/yiisoft/multiparser/YiiMultiparser.php @@ -17,27 +17,29 @@ use yii\base\Component; class YiiMultiparser extends Component{ public $configuration; +public $parserHandler; - public function getConfiguration($extension, $conf_parameter){ - - if (!isset( $this->configuration[$extension] )){ - throw new \ErrorException( "Parser do not maintain file with extension {$extension}"); - } - if (!isset( $this->configuration[$extension][$conf_parameter] )){ - throw new \ErrorException( "Parser configurator do not have settings for {$conf_parameter} parameter"); - } - - return $this->configuration[$extension][$conf_parameter]; + public function init() + { + parent::init(); + $this->parserHandler = new YiiParserHandler( ); + $this->parserHandler->setConfiguration( $this->configuration ); } public function parse( $filePath, $options = [] ){ - $parser = new YiiParserHandler( $filePath, $options ); - return $parser->run(); + $this->parserHandler->setup( $filePath, $options ); + + return $this->parserHandler->run(); } + public function getConfiguration( $extension, $parameter ){ + + return $this->parserHandler->getCustomConfiguration( $extension, $parameter ); + + } } \ No newline at end of file diff --git a/vendor/yiisoft/multiparser/YiiParserHandler.php b/vendor/yiisoft/multiparser/YiiParserHandler.php index 5bf86ad..d23e2e3 100644 --- a/vendor/yiisoft/multiparser/YiiParserHandler.php +++ b/vendor/yiisoft/multiparser/YiiParserHandler.php @@ -17,68 +17,74 @@ class YiiParserHandler extends ParserHandler{ /** * @param $filePath * @param array $options - * проверяет читабенльность переданного файла, а также наличие настроек парсера в конфигурационном файле для данного типа файла + * проверяет читабельность переданного файла, а также наличие настроек парсера в конфигурационном файле для данного типа файла */ - public function __construct($filePath, $options = []) +// public function setup($filePath, $options = []) +// { +// $this->filePath = $filePath; +// if (isset($options['mode'])) { +// +// $this->mode = $options['mode']; +// unset($options['mode']); +// +// } else { +// +// $this->mode = self::DEFAULT_MODE; +// +// } +// +// $this->options = $options; +// +// try { +// $this->fileObject = new \SplFileObject($this->filePath, 'r'); +// } catch (\ErrorException $e) { +// // Yii::warning("Ошибка открытия файла {$this->filePath}"); +// echo "Ошибка открытия файла {$this->filePath}"; +// return []; +// } +// +// $options['file'] = $this->fileObject; +// $this->extension = $this->fileObject->getExtension(); +// +// try { +// +// $this->configuration = array_merge_recursive ($this->configuration, $options); +// +// } catch (\ErrorException $e) { +// echo $e->getMessage(); +// return []; +// } +// +// } +// +// public function run() +// { +// +// $result = []; +// +// // \common\components\CustomVarDamp::dumpAndDie($this); +// if (count($this->configuration)) { +// $parser = \Yii::createObject($this->configuration); +// +// try { +// +// $parser->setup(); +// $result = $parser->read(); +// +// } catch (\ErrorException $e) { +// +// echo $e->getMessage(); +// +// } +// +// } +// +// return $result; +// } + protected function createObjectByConfiguration($configuration) { - $this->filePath = $filePath; - if (isset($options['mode'])) { - - $this->mode = $options['mode']; - unset($options['mode']); - - } else { - - $this->mode = self::DEFAULT_MODE; - - } - - $this->options = $options; - - try { - $this->fileObject = new \SplFileObject($this->filePath, 'r'); - } catch (\ErrorException $e) { - // Yii::warning("Ошибка открытия файла {$this->filePath}"); - echo "Ошибка открытия файла {$this->filePath}"; - return []; - } - - $options['file'] = $this->fileObject; - $this->extension = $this->fileObject->getExtension(); - - try { - $this->configuration = \Yii::$app->multiparser->getConfiguration($this->extension, $this->mode); - $this->configuration = array_merge_recursive ($this->configuration, $options); - } catch (\ErrorException $e) { - echo $e->getMessage(); - return []; - } - + return \Yii::createObject($configuration); } - public function run() - { - - $result = []; - - // \common\components\CustomVarDamp::dumpAndDie($this); - if (count($this->configuration)) { - $parser = \Yii::createObject($this->configuration); - - try { - - $parser->setup(); - $result = $parser->read(); - - } catch (\ErrorException $e) { - - echo $e->getMessage(); - - } - - } - - return $result; - } } \ No newline at end of file -- libgit2 0.21.4