Messages.php 2.86 KB
<?php
/**
 * Created by PhpStorm.
 * User: Zip
 * Date: 15/4/19
 * Time: 下午7:29
 */

namespace Hood\Helper\Validation;


class Messages
{
    private $messages = array();

    private $_customMessages = array();

    private $defaultMessagesLanguage = array();

    public function __construct(array $customMessages = array())
    {
        $this->defaultMessagesLanguage = Language::$messages;
        $this->customMessages($customMessages);
    }

    /**
     * TODO 自定义数据
     * xxx.required=>'xxx'
     * xxx.min=>'xxx'
     *
     * 设置自定义消息
     * @param array $customMessages
     */
    public function customMessages(array $customMessages = array())
    {
        $this->_customMessages = $customMessages;
    }

    /**
     * 设置一条自定义消息
     * @param $key
     * @param $message
     * @return $this
     */
    public function add($key, $message)
    {
        $this->_customMessages[$key] = $message;
        return $this;
    }

    /**
     * 获取所有错误
     * @return array
     */
    public function all()
    {
        $all = array();
        foreach ($this->messages as $key => $messages) {
            $all = array_merge($all, $messages);
        }
        return $all;
    }

    /**
     * 存储消息
     * @param $key
     * @param $val
     */
    public function setMessages($key, $val)
    {
        $this->messages[$key][] = $val;
    }

    /**
     * 查看所有字段的所有错误信息
     * @param $key
     * @return array
     */
    public function get($key)
    {
        if (isset($this->messages[$key])) {
            return $this->messages[$key];
        }
        return array();
    }

    /**
     * 判断是否有错误信息
     * @return bool
     */
    public function has($key = null)
    {
        if ($key == null) {
            return count($this->messages) > 0;
        }
        return isset($this->messages[$key]);
    }

    /**
     * 第一个错误
     * @param $key
     * @return array
     */
    public function first($key = null)
    {
        if (is_null($key) && count($this->messages) > 0) {
            $messages = array_slice($this->messages, 0, 1);
            return $messages[key($messages)][0];
        }
        $messages = $this->get($key);
        return (count($messages) > 0) ? $messages[0] : '';
    }

    /**
     * 获取消息
     * @param $key
     * @param null $type
     * @return string
     */
    public function getMessages($key, $type = null)
    {
        if (isset($this->_customMessages[$key])) {
            return $this->_customMessages[$key];
        } elseif (array_key_exists($key, $this->defaultMessagesLanguage)) {
            if (isset($this->defaultMessagesLanguage[$key][$type])) {
                return $this->defaultMessagesLanguage[$key][$type];
            }
            return $this->defaultMessagesLanguage[$key];
        }
        return '';
    }
}