ParserController.php 4.67 KB
<?php
namespace console\controllers;

use common\components\CustomVarDamp;
use yii\console\Controller;
use yii\helpers\Console;
use common\components\PriceWriter;
use backend\models\ImportersFiles;
use backend\models\Importers;
use yii\base\ErrorException;

class ParserController extends Controller
{
    public function actionParseCsv()
    {
        \Yii::info('Начало загрузки файлов прайсов csv', 'parser');
        foreach (glob(\Yii::getAlias('@auto_upload') . '/*.csv') as $file_path) {
            $file_name = basename($file_path, ".csv");
            \Yii::info("Обработка файла - $file_path", 'parser');
            $importer_id = ImportersFiles::findOne(['id' => $file_name])->importer_id;
            $current_importer = Importers::findOne(['id' => $importer_id]);
            $keys = $current_importer->keys;
            $mult_array = $current_importer->multiply;

            // получим настройки ценообразования и передадим их отдельно в конвертер
            $sign = '';
            $multiplier = '';
            extract( $mult_array );


            $config = ['record_id' => $file_name,
                'importer_id' => $importer_id,
                'parser_config' => ['keys' => $keys,
                    'converter_conf' =>
                    ['sign' => $sign,
                    'multiplier' => $multiplier],
                    'mode' => 'console']
            ];
            if ($this->parseFileConsole($file_path, $config)) {
                unlink(\Yii::getAlias('@temp_upload') . '/' . $file_name . '.csv');
                \Yii::info("Загрузка файла - $file_path успешно завершена", 'parser');
            } else {
                \Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser');
            }
            //при любом завершении скрипта файл с очереди автозагрузки нужно удалить
            unlink(\Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv');
        }

    }


    protected function parseFileConsole( $file_path, $configuration ){

        if( !file_exists( $file_path ) )
            throw new ErrorException("$file_path - файл не найден!");

        $parser_config = [];
        if ( isset( $configuration['parser_config'] ) ) {
            $parser_config = $configuration['parser_config'];
        }
        $data = \Yii::$app->multiparser->parse( $file_path, $parser_config );
        if ( ! $data ) {
            // @todo переделать, что бы ошибка автоматически останавливала сценарий
            return false;
        }

        $writer = new PriceWriter();
        $writer->configuration = $configuration;
        $writer->data = $data;
        $writer->mode = 1; //console-режим

        if ( $writer->writeDataToDB() ){

            return true;
        }

        return false;
    }

    public function actionParseXml ()
    {
         \Yii::info('Начало загрузки файлов прайсов xml', 'parser');
        foreach (glob(\Yii::getAlias('@auto_upload') . '/*.xml') as $file_path) {
            $file_name = basename($file_path, ".xml");
                  \Yii::info("Обработка файла - $file_path", 'parser');

            $files_model = new ImportersFiles();
            // id поставщика всегда = 1 - Склад
            $files_model->importer_id = 1;
            try {
                $files_model->save();
            } catch (ErrorException  $e) {
                throw $e;
            }
            // получим id только что записанной записи
            $record_id = $files_model->find()
                ->where(['importer_id' => $files_model->importer_id])
                ->orderBy(['id' => SORT_DESC])
                ->one()
                ->id;

            $config = ['record_id' => $record_id,
                'importer_id' => 1,
                'parser_config' => [
                    'mode' => 'console']
            ];

            if ($this->parseFileConsole($file_path, $config)) {
                unlink(\Yii::getAlias('@auto_upload') . '/' . $file_name . '.xml');
                        \Yii::info("Загрузка файла - $file_path успешно завершена", 'parser');
            } else {
                        \Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser');
            }
        }
    }

    public function actionTest()
    {
        Console::output('It is working ');
        \Yii::info('2', 'parser');

    }
}