<?php
/**
 * Created by PhpStorm.
 * User: Ming
 * Date: 2017/10/18
 * Time: 11:42
 */

namespace common\traits;

use Yii;
use yii\helpers\Json;
use common\widgets\Alert;

trait NoticeTrait {

    /**
     * 发送通知
     * @param $message
     * @param string $attr
     * @param null $extend
     * @param int $code
     * @return array
     */
    public function notice($message, $attr = 'error', $extend = null, $code = 200){
        if($attr != 'success'){
            Yii::$app->response->setStatusCode(422);
            $error = 1;
        }else{
            $error = 0;
        }
        $type = (!$extend) ? $attr : $extend;
        $response = ['code' => $code, 'message' => $message, 'error' => $error, 'type' => $type];
        return $response;
    }
    /**
     * 魔术方法
     * @param $name
     * @param $params
     * @return bool
     */
    public function __call($name, $params){
        $types = (new Alert())->alertTypes;
        if(!array_key_exists($name, $types)){
            return false;
        }
        $code = (isset($params[2])) ? $params[2] : 200;
        $extend = isset($params[1]) ? $params[1] : null;
        return $this->notice($params[0], $name, $extend, $code);
    }
}