<?php
/**
 * Created by PhpStorm.
 * User:  NODELOG
 * Date: 16/3/2
 * Time: 下午2:07
 */

namespace api\common\controllers;

use api\common\behaviors\ValidateBehavior;
use common\enums\CodeEnum;
use Yii;
use yii\filters\Cors;
use yii\rest\Serializer;
use yii\web\ServerErrorHttpException;

class Controller extends \yii\rest\Controller
{
    /**
     * 配置让dataProvider序列化后使用data统一接收
     * @var array
     */
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'data'
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        unset($behaviors['contentNegotiator']);
        $behaviors['cors'] = [
            'class' => Cors::className(),
        ];
        $behaviors['validate'] = ValidateBehavior::className();
        return $behaviors;
    }


    /**
     * 重写serializeData 函数，格式化返回数据 model序列号后使用data统一接收
     * @param mixed $data
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @author nodelog
     */
    protected function serializeData($data)
    {
        /* @var Serializer $serializer */
        $serializer = Yii::createObject($this->serializer);

        if (is_array($data) && isset($data['data'])) {
            $data['data'] = $serializer->serialize($data['data']);
        }

        //序列化数据
        $data = $serializer->serialize($data);

        //接口版本号
        $data['version'] = Yii::$app->config->get('version');

        return $data;
    }
}