确实,传递标头名称是“危险的” - 作为 的参数withHeader()
,
这同样适用于标头值参数。它必须是数组或字符串(仅表示一个值,而不是逗号分隔的值列表!)。
至于withHeader
方法的实现:
/**
* Return an instance with the provided value replacing the specified header.
*
* ...
*
* @param string $name Case-insensitive header field name.
* @param string|string[] $value Header value(s).
* @return static
* @throws \InvalidArgumentException for invalid header names or values.
*/
public function withHeader($name, $value) {
$this
->validateHeaderName($name)
->validateHeaderValue($value)
;
$clone = clone $this;
$clone->replaceHeader($name, $value);
return $clone;
}
/**
* =================
* Not part of PSR-7
* =================
*
* Validate header name.
*
* @param string $name Case-insensitive header field name.
* @return $this
* @throws \InvalidArgumentException
*/
protected function validateHeaderName($name) {
if (!isset($name)) {
throw new \InvalidArgumentException('No header name provided!');
}
if (!is_string($name)) {
throw new \InvalidArgumentException('The header name must be a string!');
}
if (empty($name)) {
throw new \InvalidArgumentException('Empty header name provided!');
}
return $this;
}
/**
* =================
* Not part of PSR-7
* =================
*
* Validate header value.
*
* @param string|string[] $value Header value(s).
* @return $this
* @throws \InvalidArgumentException
*/
protected function validateHeaderValue($value) {
if (isset($value) && !is_array($value) && !is_string($value)) {
throw new \InvalidArgumentException('The header value must be a string or an array!');
}
return $this;
}
/**
* =================
* Not part of PSR-7
* =================
*
* Replace a header item with a new one.
*
* @param string $name Case-insensitive header field name.
* @param string|string[] $value Header value(s).
* @return $this
* @done
*/
protected function replaceHeader($name, $value) {
$this
->removeHeader($name)
->addHeader($name, $value)
;
return $this;
}