有控制器
FakeController
,它必须按请求接受 JSON 和明文:
public function check(Request $request, int $twin): mixed {
echo "twin = " . $twin . PHP_EOL;
echo "request = " . print_r($request, true) . PHP_EOL;
return null;
}
使用 JSON 调用此方法:
app(FakeController::class)->check(new Request($json), 123);
成功 -
check
内的所有回显均已达到并打印预期数据。
然后尝试用明文调用方法
check
:
$message = 'some text';
app(FakeController::class)->check(new Request($message), 123);
check
默默地遥不可及。
猜猜这就是为什么 new Request($message)
产生了几乎空的请求,里面没有“一些文本”。
那么,如何创建带有明文正文的请求?
我知道如何使用 Http 客户端,但 Http 客户端主要用于外部调用。
这就是工作:
//$message = scalar or JSON-string
$maybeTwin = 123
$maybeJSON = json_decode($message, true);
if (is_array($maybeJSON)) { // JSON here
$request = new Request($maybeJSON);
$request->headers->set('Content-Type', 'application/json');
$result = app(FakeController::class)->check($request, $maybeTwin);
} else { // scalar value here
$request = new Request(content: $message);
$request->headers->set('Content-Type', 'text/plain');
$result = app(FakeController::class)->check($request, $maybeTwin);
}