<?php

namespace Mainto\RpcServer\RpcServer\ContextTrait;

trait HeaderTrait {
    protected array $responseHeaders = [];
    protected array $requestHeaders = [];

    /**
     * 添加响应头
     *
     * @param $name
     * @param $value
     */
    public function addResponseHeader ($name, $value) {
        $name = strtolower($name);
        if ($name == "set-cookie") {
            if (!is_array($value)) {
                $value = [$value];
            }

            if (isset($this->responseHeaders[$name])) {
                $value = array_values(array_merge($this->responseHeaders[$name], $value));
            }
        }

        $this->responseHeaders[$name] = $value;
    }

    /**
     * 设置状态码
     *
     * @param int $statusCode
     */
    public function setStatusCode (int $statusCode) {
        $this->responseHeaders['status-code'] = (int)$statusCode;
    }

    /**
     * 跳转地址
     *
     * @param string $url
     * @param int $status
     */
    public function redirect (string $url, int $status = 302) {
        $this->setStatusCode($status);
        $this->addResponseHeader("Location", $url);
    }

    /**
     * 获取响应头
     *
     * @param $name
     * @param null $default
     * @return array
     */
    public function getResponseHeader ($name = null, $default = null) {
        if (!$name) {
            return $this->responseHeaders;
        }

        return $this->responseHeaders[$name] ?? $default;
    }

    /**
     * 是否有头信息
     *
     * @param $key
     * @return bool
     */
    public function hasHeader ($key) {
        return isset($this->requestHeaders[$key]);
    }

    /**
     * 获取每个头信息
     * @param $key
     * @return null
     */
    public function getHeader ($key) {
        return $this->requestHeaders[$key] ?? null;
    }
}