You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
http/src/Context/ResponseTraits.php

54 lines
1.4 KiB
PHP

<?php
namespace BitCommunism\Http\Context;
use Dflydev\FigCookies\SetCookie;
use Dflydev\FigCookies\SetCookies;
use Psr\Http\Message\ResponseInterface;
use function GuzzleHttp\Psr7\stream_for;
trait ResponseTraits
{
/**
* @var SetCookies
*/
private $setCookies;
public function json($obj, $options = 0, $depth = 512): void
{
$this->withResponse(function (ResponseInterface $response) use ($obj, $options, $depth) {
return $response->withHeader('Content-Type', 'application/json')
->withBody(stream_for(json_encode($obj, $options, $depth)));
});
}
public function redirect($to, $status = 302): void
{
$this->withResponse(function (ResponseInterface $response) use ($to, $status) {
return $response->withStatus($status)->withHeader('Location', $to);
});
}
public function getSetCookies(): SetCookies {
if ($this->setCookies === null) {
$this->setCookies = SetCookies::fromResponse($this->getResponse());
}
return $this->setCookies;
}
public function setCookie($name, $value) {
$this->addCookie(SetCookie::create($name, $value));
}
public function addCookie(SetCookie $cookie) {
$this->setCookies = $this->setCookies->with($cookie);
}
public function renderResponse() {
return $this->setCookies->renderIntoSetCookieHeader(parent::renderResponse());
}
}