ParserTrait.php 3.06 KB
<?php
/**
 * Created by PhpStorm.
 * User: Tsurkanov
 * Date: 01.12.2015
 * Time: 9:42
 */
namespace backend\components\traits;

use common\components\parsers\DynamicFormHelper;
use Yii;
use yii\base\ErrorException;
use yii\data\ArrayDataProvider;

trait ParserTrait
{

    /**
     * @param $mode - int: 0 - fetch from cache, - 1 - put in cache,  <2 - delete from cache
     * @param $data - array
     * @param $configuration - array
     * @throws \ErrorException
     */
    public function parserCacheHandler($mode, &$data = [], &$configuration = [])
    {
        switch ($mode) {
            case 0:
                if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) {
                    $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
                    $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration'));
                } else {
                    throw new \ErrorException('Ошибка кеша');
                }
                break;

            case 1:
                Yii::$app->getCache()->set('parser_data', json_encode($data), 1800);
                // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
                Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800);
                break;

            default:
                if (Yii::$app->getCache()->exists('parser_data'))
                    Yii::$app->getCache()->delete('parser_data');

                if (Yii::$app->getCache()->exists('parser_configuration'))
                    Yii::$app->getCache()->delete('parser_configuration');
        }

    }

    public function renderResultView($data)
    {
        $provider = new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 10,
            ],
        ]);

        // создадим модель на столько реквизитов сколько колонок в отпарсенном файле
        $last_index = end(array_flip($data[0]));
        $header_counts = $last_index + 1;
        $header_model = DynamicFormHelper::CreateDynamicModel($header_counts);

        // соберем массив данных из которых будет пользователь выбирать значения в конструкторе (выпадающий список)
        $basicColumns = $this->getBasicColumns();

        return $this->render('results',
            ['model' => $data,
                'header_model' => $header_model,
                // список колонок для выбора
                'basic_column' => $basicColumns,
                'dataProvider' => $provider]);

    }

    public function throwStringErrorException( $model , $exception, $errors_str = '' )
    {
        foreach ( $model->getErrors() as $error )
        {
            $errors_str .= ' ' . implode( array_values( $error ) );
        }

        throw new $exception( $errors_str );
    }

    }