ParserController.php 2.37 KB
<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use backend\models\UploadFileParsingForm;
use yii\web\UploadedFile;
use yii\data\ArrayDataProvider;
use app\components\parsers\ParserHandler;

/**
 * Site controller
 */
class ParserController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        Yii::$app->controller->enableCsrfValidation = false;
        $model = new UploadFileParsingForm();

        if (Yii::$app->request->isPost) {

            $model->file = UploadedFile::getInstance($model, 'file');

            if ($model->file && $model->validate()) {
                $filePath = Yii::getAlias('@webroot') . '/uploads/' . $model->file->baseName . '.' . $model->file->extension;
                $model->file->saveAs( $filePath );

                $parser = new ParserHandler( $filePath, 1 );
                $data = $parser->run();

                if( !is_array($data) ){
                    $data = ['No results'];
                }
                $provider = new ArrayDataProvider([
                    'allModels' => $data,
                    'pagination' => [
                        'pageSize' => 10,
                    ],
//                    'sort' => [
//                        'attributes' => ['id', 'name'],
//                    ],
                ]);

                return $this->render('results',
                    ['model' => $data,
                        'dataProvider' => $provider]);
            }
        }

        return $this->render('index', ['model' => $model]);
    }



}